C# 高级特性(二):反射(Reflection)

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

 //反射(Reflection)有下列用途:

        //1它允许在运行时查看特性(attribute)信息。

        

        public static void ShowAttribute()
        {
            System.Reflection.MemberInfo info = typeof(AttributeNS.Rectangle);
            //显示类特性
            object[] attributes = info.GetCustomAttributes(true);
            System.Console.WriteLine("类特性 attr count:" + attributes.Length);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i].ToString());
            }
            //System.Console.WriteLine("");

            // 遍历方法特性
            Type type = typeof(AttributeNS.Rectangle);
            System.Console.WriteLine("方法的特性 ");
            foreach (var item in type.GetMethods())
            {
                foreach (Attribute a in item.GetCustomAttributes(true))
                {
                    System.Console.WriteLine(a.ToString());
                }
                System.Console.WriteLine("");
            }
        }

运行结果如下;

              

 

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

        public static void TypeList()
        {
            // 初始化一个不同类型的集合
            //  这些类都有一个独有的方法
            object[] olist = new object[] { new ClassA(), new ClassB(), new ClassC() };
            List<object> olist2 = new List<object>();
            System.Console.WriteLine("对象列表:");
            foreach (var o in olist)
            {
                // 用反射读取该类型的所有方法名
                Type type = o.GetType();
                foreach (var function in type.GetMethods())
                {
                    if (function.Name.ToLower().Contains("show"))
                        System.Console.WriteLine(type.Name + ":" + function.Name);
                }
                // 用这个类型再实例化一个。
                //使用无参构造函数创建对象
                Assembly asm = Assembly.GetExecutingAssembly();//获取当前代码所在程序集
                Object obj = asm.CreateInstance(type.FullName, true);//创建一个对象TestClass对象
                olist2.Add(obj);
            }
            System.Console.WriteLine("");
            System.Console.WriteLine("再实例化:");

            System.Console.WriteLine("对象列表:");
            //  展示再实例化的对象
            foreach (var o in olist2)
            {
                Type type = o.GetType();
                foreach (var function in type.GetMethods())
                {
                    if (function.Name.ToLower().Contains("show"))
                        System.Console.WriteLine(type.Name+":"+function.Name);
                }
            }
        }

运行结果:

 

 

        //3它允许延迟绑定的方法和属性(property)。

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

    }

正文中用到的类:

    public class ClassShow
    {
        public int classNo = 0;
        public override string ToString()
        {
            return "classNo:" + classNo;
        }
    }

    public class ClassA : ClassShow
    {
        public void showA()
        {

        }
    }
    public class ClassB : ClassShow
    {
        public void showB()
        {

        }
    }
    public class ClassC : ClassShow
    {
        public void showC()
        {

        }
    }
 [AttributeUsage(AttributeTargets.Class |
        AttributeTargets.Constructor |
        AttributeTargets.Field |
        AttributeTargets.Method |
        AttributeTargets.Property,/*作用域,程序集 或变量*/
        AllowMultiple = true,/*参数 allowmultiple(可选的)为该特性的 AllowMultiple 属性(property)提供一个布尔值。
                             * 如果为 true,则该特性是多用的。默认值是 false(单用的)。*/
         Inherited = true   /*参数 inherited(可选的)为该特性的 Inherited 属性(property)提供一个布尔值。
                             * 如果为 true,则该特性可被派生类继承。默认值是 false(不被继承)。*/
        )]
    public class DeBugInfo : System.Attribute
    {
        private int bugNo;
        private string developer;
        private string lastReview;
        public string message;

        public DeBugInfo(int bg, string dev, string d)
        {
            this.bugNo = bg;
            this.developer = dev;
            this.lastReview = d;
        }

        public int BugNo
        {
            get 
            {
                return bugNo;
            }
        }
        public string Developer
        {
            get
            {
                return developer;
            }
        }
        public string LastReview
        {
            get
            {
                return lastReview;
            }
        }
        public string Message
        {
            get
            {
                return message;
            }
            set
            {
                message = value;
            }
        }
        public override string ToString()
        {
            return "bugNo:"+ bugNo+ "\tDeveloper:"+ Developer + "\tLastReview:"+ LastReview + "\tmessage:"+ message ;
        }
    }

    [DeBugInfo(54, "Zara Ali", "11/10/2012",
    Message = "class Rectangle")]
    public class Rectangle
    {
        // 成员变量
        protected double length;
        protected double width;
        public Rectangle(double l, double w)
        {
            length = l;
            width = w;
        }
        //自定义 特性:
        [DeBugInfo(55, "Zara Ali", "19/10/2012",
        Message = "Return type mismatch")]
        public double GetArea()
        {
            return length * width;
        }

        //自定义 特性,可记录 信息,可以使用反射读取 。
        [DeBugInfo(56, "Zara Ali", "19/10/2012")]
        public void Display()
        {
            Console.WriteLine("Length: {0}", length);
            Console.WriteLine("Width: {0}", width);
            Console.WriteLine("Area: {0}", GetArea());
        }

        // 类似条件编译,但没有定义符号 时编译不会报错
        [Conditional("DEBUG")]
        public static void Message(string msg)
        {
            Console.WriteLine(msg);
        }

        // 标记的方法会被编译器视为错误或 警告  
        [Obsolete("过时的 方法", true)]
        public static void ShowMessage(string msg)
        {
            Console.WriteLine(msg);
        }
    }

 

    

参考:

  1. 菜鸟教程 :https://www.runoob.com/csharp/csharp-reflection.html
  2. C#反射-动态创建对象

————————————————

版权声明:本文为CSDN博主「小何同学_」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/heyangyi_19940703/article/details/51346357  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值