C#如何使用反射机制实现延迟绑定

今天小编给大家分享一下C#如何使用反射机制实现延迟绑定的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

反射允许我们在编译期或运行时获取程序集的元数据,通过反射可以做到:

● 创建类型的实例
● 触发方法
● 获取属性、字段信息
● 延迟绑定
......

如果在编译期使用反射,可通过如下2种方式获取程序集Type类型:

  • 1、Type类的静态方法

Type type = Type.GetType("somenamespace.someclass");

  • 2、通过typeof

Type type = typeof(someclass);

如果在运行时使用反射,通过运行时的Assembly实例方法获取Type类型:

Type type = asm.GetType("somenamespace.someclass");

获取反射信息

有这样的一个类:

    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public float Score { get; set; }

        public Student()
        {
            this.Id = -1;
            this.Name = string.Empty;
            this.Score = 0;
        }

        public Student(int id, string name, float score)
        {
            this.Id = id;
            this.Name = name;
            this.Score = score;
        }

        public string DisplayName(string name) 
        {
            return string.Format("学生姓名:{0}", name);
        }

        public void ShowScore()
        {
            Console.WriteLine("学生分数是:" + this.Score);
        }
    }

通过如下获取反射信息:

        static void Main(string[] args)
        {
            Type type = Type.GetType("ConsoleApplication1.Student");
            //Type type = typeof (Student);

            Console.WriteLine(type.FullName);
            Console.WriteLine(type.Namespace);
            Console.WriteLine(type.Name);

            //获取属性
            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {
                Console.WriteLine(prop.Name);
            }

            //获取方法
            MethodInfo[] methods = type.GetMethods();
            foreach (MethodInfo method in methods)
            {
                Console.WriteLine(method.ReturnType.Name);
                Console.WriteLine(method.Name);
            }
            Console.ReadKey();
        }

 延迟绑定

在通常情况下,为对象实例赋值是发生在编译期,如下:

Student stu = new Student();
stu.Name = "somename";

而"延迟绑定",为对象实例赋值或调用其方法是发生在运行时,需要获取在运行时的程序集、Type类型、方法、属性等。

            //获取运行时的程序集
            Assembly asm = Assembly.GetExecutingAssembly();

            //获取运行时的Type类型
            Type type = asm.GetType("ConsoleApplication1.Student");

            //获取运行时的对象实例
            object stu = Activator.CreateInstance(type);

            //获取运行时指定方法
            MethodInfo method = type.GetMethod("DisplayName");
            object[] parameters = new object[1];
            parameters[0] = "Darren";

            //触发运行时的方法
            string result = (string)method.Invoke(stu, parameters);
            Console.WriteLine(result);
            Console.ReadKey();

以上就是“C#如何使用反射机制实现延迟绑定”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接