C#反射(reflection)

反射是.Net中的重要机制,通过反射可以得到“.exe”或“.dll”等程序集内部的接口、类、方法、字段、属性、特性等信息,还可以动态创建出类型实例并执行其中的方法。

反射指程序可以访问、检测和修改它本身状态或行为的一种能力。程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。

可以使用反射动态的创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。

1 获取Type类型对象

            //通过反射获取类型
            //1.通过typeof(类型)获取Type
            Type type = typeof(Person);

            //2.通过对象调用GetType()方法
            Person p = new Person();
            type = p.GetType();

            //3.通过类名称字符串,注意类名称要全(包含命名空间的)
            Type? t = System.Type.GetType("RedisHelper.Person");

2 Type类中的属性

            //1.通过typeof(类型)获取Type
            Type type = typeof(Person);

            //Type类的属性和方法
            Console.WriteLine("Name:" + type.Name);
            Console.WriteLine("FullName:" + type.FullName);
            Console.WriteLine("Namespace:" + type.Namespace);
            Console.WriteLine("IsAbstract:" + type.IsAbstract);
            Console.WriteLine("IsArray:" + type.IsArray);
            Console.WriteLine("IsClass:" + type.IsClass);
            Console.WriteLine("IsInterface:" + type.IsInterface);
            Console.WriteLine("IsPublic:" + type.IsPublic);
            Console.WriteLine("IsSealed:" + type.IsSealed);
            Console.WriteLine("IsValueType:" + type.IsValueType);
            Console.WriteLine("BaseType:" + type.BaseType);
            Console.WriteLine("AssemblyQualifiedName:" + type.AssemblyQualifiedName);

3 反射的用途

它允许在运行时查看特性信息。

它允许审查集合中的各种类型,以及实例化这些类型。

它允许延迟绑定的方法和属性。

它允许在运行时创建新类型,然后使用这些类型执行一些任务。

首先我们有这么一个类:

    public class Person
    {
        private int id;
        public int Id { get => id; set => id = value; }
        public string Name { get; set; }

        public int Age { get; set; }

        public override string ToString()
        {
            return $"Id:{Id},Name:{Name},Age:{Age}";
        }

        public Person()
        {

        }
        public Person(int id,string name,int age)
        {
            this.id = id;
            this.Name = name;
            this.Age = age;
        }

        public string GetName()
        {
            return this.Name;
        }

        public string GetName(string name)
        {
            return this.Name + name;
        }

        private void Method(string str)
        {
            Console.WriteLine("i am a private method,thi args of str:" + str);
        }
    }
3.1 创建实例
            //获取类型
            Type type = typeof(Person);

            //创建实例,无参构造
            object o1 = Activator.CreateInstance(type);
            Person p1 = o1 as Person;
            Console.WriteLine(p1.ToString());

            //创建实例,调用带参构造
            object o2 = Activator.CreateInstance(type, new object[] { 0x02, "zhangjuan", 18 });
            Person p2 = o2 as Person;
            Console.WriteLine(p2.ToString());
3.2 调用方法
            //获取类型
            Type type = typeof(Person);

            //创建实例,调用带参构造
            object o2 = Activator.CreateInstance(type, new object[] { 0x02, "zhangjuan", 18 });
            Person p2 = o2 as Person;
            Console.WriteLine(p2.ToString());

            MethodInfo method = type.GetMethod("GetName", new Type[] { typeof(string) });
            object result = method.Invoke(o2, new object[] { "hahaha" });
            Console.WriteLine(result);

这里有一个问题,调用的是重载方法,在获取方法信息的时候,传入了参数类型的参数。但是如果获取那个重载的无参的方法直接报错了。

当调用私有方法的时候,获取方法信息的时候还需要另外一组参数。

            //获取类型
            Type type = typeof(Person);

            //创建实例,调用带参构造
            object o2 = Activator.CreateInstance(type, new object[] { 0x02, "zhangjuan", 18 });
            Person p2 = o2 as Person;
            Console.WriteLine(p2.ToString());

            MethodInfo method = type.GetMethod("Method",BindingFlags.Instance|BindingFlags.NonPublic);
            object result = method.Invoke(o2, new object[] { "hahaha" });
            Console.WriteLine(result);
3.3 获取与修改成员变量
            //获取类型
            Type type = typeof(Person);

            //创建实例,调用带参构造
            object o2 = Activator.CreateInstance(type, new object[] { 0x02, "zhangjuan", 18 });
            Person p2 = o2 as Person;
            Console.WriteLine(p2.ToString());

            PropertyInfo property = type.GetProperty("Name");
            Console.WriteLine(property.GetValue(o2));
            property.SetValue(o2, "zhangjuanbb");
            Console.WriteLine(property.GetValue(o2));

            FieldInfo field = type.GetField("id", BindingFlags.Instance | BindingFlags.NonPublic);
            Console.WriteLine(field.GetValue(o2));
            field.SetValue(o2, 0x09);
            Console.WriteLine(field.GetValue(o2));
3.4 创建泛型类并调用
    public class Person<T1, T2>
    {
        public T1 TT1 { get; set; }
        public T2 TT2 { get; set; }

        public void Foo<A, B>(A a, B b)
        {
            Console.WriteLine($"A的类型为:{a.GetType().Name},a的值为:{a.ToString()}");
            Console.WriteLine($"B的类型为:{b.GetType().Name},b的值为:{b.ToString()}");
        }
    }
            Type type = typeof(Person<string, int>);

            object o = Activator.CreateInstance(type);


            MethodInfo method = type.GetMethod("Foo");
            method = method.MakeGenericMethod(new Type[] { typeof(string), typeof(int) });
            method.Invoke(o, new object[] { "zhudaokuan", 100 });
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值