zoukankan      html  css  js  c++  java
  • 特性与反射

      自定义特性

      [AttributeUsage(AttributeTargets.All)]
        public class HelpAttribute : System.Attribute
        {
            private string topic;
            public readonly string Url;
    
            public string Topic  // Topic 是一个命名(named)参数
            {
                get
                {
                    return topic;
                }
                set
                {
    
                    topic = value;
                }
            }
    
            public HelpAttribute(string url)  // url 是一个定位(positional)参数
            {
                this.Url = url;
            }
        }

    使用

    [HelpAttribute("MyClassHelpAttributeUrl")]
        [MyClassAttribute("MyClassAttributeName")]
        public class MyClass
        {
            [Conditional("DEBUG")]
            public static void Message(string msg)
            {
                Console.WriteLine(msg);
            }
            [Obsolete("Don't use OldMethod, use NewMethod instead", true)]
            public static void OldMethod()
            {
                Console.WriteLine("It is the old method");
            }
            public static void NewMethod()
            {
                Console.WriteLine("It is the new method");
            }
        }

    通过反射调用

                System.Reflection.MemberInfo info = typeof(MyClass);
                object[] attributes = info.GetCustomAttributes(true);
                for (int i = 0; i < attributes.Length; i++)
                {
                    System.Console.WriteLine(attributes[i]);
                }

    反射实例

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FansheModel
    {
        [AttributeUsage(AttributeTargets.Class
                        |AttributeTargets.Constructor
                        | AttributeTargets.Field
                        | AttributeTargets.Property
                        | AttributeTargets.Method
                        ,AllowMultiple =true)]
        public class DeBugInfo:System.Attribute
        {
            private int bugNo; //bug编号
            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 void ShowHelloWorld()
          {
            Console.WriteLine("Hello World!");
          }
          public void ShowHelloWorldParam(string str)
          {
            Console.WriteLine(str);
          }

    
    

          public static void ShowStatic(string str)
          {
            Console.WriteLine(str);
          }

    
    

          public void Show3()
          {
            Console.WriteLine("我是Show3");
          }
          public void Show3(int id)
          {
            Console.WriteLine("我是Show3,int参数");
          }
          public void Show3(string str)
          {
            Console.WriteLine("我是Show3,string参数");
          }
          public void Show3(int id,string str)
          {
            Console.WriteLine("我是Show3,带两个参数int和string");
          }

    
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FansheModel
    {
        [DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
        [DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
       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());
            }
        }
    }

    调用

                Rectangle r = new Rectangle(4.5, 7.5);
                r.Display();
                Type type = typeof(Rectangle);
                // 遍历 Rectangle 类的特性
                foreach (Object attributes in type.GetCustomAttributes(false))
                {
                    DeBugInfo dbi = (DeBugInfo)attributes;
                    if (null != dbi)
                    {
                        Console.WriteLine("Bug no: {0}", dbi.BugNo);
                        Console.WriteLine("Developer: {0}", dbi.Developer);
                        Console.WriteLine("Last Reviewed: {0}",
                                                 dbi.LastReview);
                        Console.WriteLine("Remarks: {0}", dbi.Message);
                    }
                }
    
                // 遍历方法特性
                foreach (MethodInfo m in type.GetMethods())
                {
                    foreach (Attribute a in m.GetCustomAttributes(true))
                    {
                        if (a is DeBugInfo)
                        {
                            DeBugInfo dbi = (DeBugInfo)a;
                            if (null != dbi)
                            {
                                Console.WriteLine("Bug no: {0}, for Method: {1}",
                                                              dbi.BugNo, m.Name);
                                Console.WriteLine("Developer: {0}", dbi.Developer);
                                Console.WriteLine("Last Reviewed: {0}",
                                                              dbi.LastReview);
                                Console.WriteLine("Remarks: {0}", dbi.Message);
                            }
    
                        }
    
                    }
                }

    通过反射动态创建datatable

    //Type t = Type.GetType("System.Data.DataTable,System.Data,Version=1.0.3300.0,  Culture=neutral,  PublicKeyToken=b77a5c561934e089");
                //DataTable table = (DataTable)Activator.CreateInstance(t);

    反射动态创建TClass

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FansheTest
    {
        class TClass
        {
    
            public string _value;
            public TClass(string value)
            {
                _value = value;
            }
    
        }
    }
      Type tts = Type.GetType("FansheTest.TClass");
                Object[] constructParms = new object[] { "hello" };  //构造器参数
                TClass obj = (TClass)Activator.CreateInstance(tts, constructParms);

    反射动态调用类里的某个函数

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace FansheTest
    {
            public class TTestClass
            {
                private string _value;
                public TTestClass()
                {
                }
                public TTestClass(string value)
                {
                    _value = value;
                }
                public string GetValue(string prefix)
                {
                    if (_value == null)
                        return "NULL";
                    else
                        return prefix + "  :  " + _value;
                }
                public string Value
                {
                    set
                    {
                        _value = value;
                    }
                    get
                    {
                        if (_value == null)
                            return "NULL";
                        else
                            return _value;
                    }
                }
            }
        
    }
                //获取类型信息
                Type t = Type.GetType("FansheTest.TTestClass");
                //构造器的参数
                object[] constuctParms = new object[] { "timmy" };
                //根据类型创建对象
                object dObj = Activator.CreateInstance(t, constuctParms);
                //获取方法的信息
                MethodInfo method = t.GetMethod("GetValue");
                //调用方法的一些标志位,这里的含义是Public并且是实例方法,这也是默认的值
                BindingFlags flag = BindingFlags.Public | BindingFlags.Instance;
                //GetValue方法的参数
                object[] parameters = new object[] { "Hello" };
                //调用方法,用一个object接收返回值
                object returnValue = method.Invoke(dObj, flag, Type.DefaultBinder, parameters, null);
                Console.WriteLine(returnValue);

    关于反射创建对象,调用里面的函数代码

     //获取FansheModel程序集下面所有的类
                Assembly assembly = Assembly.Load("FansheModel");
                foreach (var item in assembly.GetTypes())
                {
                    Console.WriteLine("我是" + item.FullName + "");
                    foreach (var propeity in item.GetProperties())
                    {
                        Console.WriteLine("我是" + item.FullName + "类中的" + propeity.Name + "属性!");
                    }
                    foreach (var method in item.GetMethods())
                    {
                        Console.WriteLine("我是"+item.FullName +"类中的"+method.Name+"方法!");
                    }
                }
                //创建对象
                Type typeDBHelper = assembly.GetType("FansheModel.DeBugInfo");//2 获取类型信息
                object[] constuctParms = new object[] {1, "timmy" ,"2019-12-04"};
                object oDBHelper = Activator.CreateInstance(typeDBHelper, constuctParms);//3 创建对象
                //调用void方法
                MethodInfo methodhello = typeDBHelper.GetMethod("ShowHelloWorld"); 
                methodhello.Invoke(oDBHelper, null);
                //带参数的void方法
                MethodInfo methodhelloparam = typeDBHelper.GetMethod("ShowHelloWorldParam");
                methodhelloparam.Invoke(oDBHelper,new object[] {"我是带参数的" });
                //静态方法
                MethodInfo methodstatic = typeDBHelper.GetMethod("ShowStatic");
                methodstatic.Invoke(null, new object[] { "我是static方法" });//静态方法第一个参数填null就可以了
                //获取重载方法
                MethodInfo methodwucan = typeDBHelper.GetMethod("Show3", new Type[] { });//代表这是无参
                methodwucan.Invoke(oDBHelper, null);
                MethodInfo methodint = typeDBHelper.GetMethod("Show3", new Type[] {typeof(int) });//代表这是int参
                methodint.Invoke(oDBHelper, new object[] { 11 });
                MethodInfo methodstring = typeDBHelper.GetMethod("Show3", new Type[] { typeof(string) });//代表这是string参
                methodstring.Invoke(oDBHelper, new object[] { "string canshu" });
                MethodInfo methodintstring = typeDBHelper.GetMethod("Show3", new Type[] { typeof(int), typeof(string) });//代表这是两种参
                methodintstring.Invoke(oDBHelper, new object[] { 111,"string canshu" });
    
                foreach (var prop in typeDBHelper.GetProperties())
                {
                    Console.WriteLine(prop.GetValue(oDBHelper));
                    Console.WriteLine(prop.Name);
                    if (prop.Name.Equals("Message"))
                    {
                        prop.SetValue(oDBHelper, "我是设置的message");
                    }
                    Console.WriteLine(prop.GetValue(oDBHelper));
                }
    
                Console.ReadKey();

     一些知识点

    反射的用途:
        (1)使用Assembly定义和加载程序集,加载在程序集清单中列出模块,以及从此程序集中查找类型并创建该类型的实例。 
        (2)使用Module了解包含模块的程序集以及模块中的类等,还可以获取在模块上定义的所有全局方法或其他特定的非全局方法。 
        (3)使用ConstructorInfo了解构造函数的名称、参数、访问修饰符(如pulic 或private)和实现详细信息(如abstract或virtual)等。 
        (4)使用MethodInfo了解方法的名称、返回类型、参数、访问修饰符(如pulic 或private)和实现详细信息(如abstract或virtual)等。
        (5)使用FiedInfo了解字段的名称、访问修饰符(如public或private)和实现详细信息(如static)等,并获取或设置字段值。
        (6)使用EventInfo了解事件的名称、事件处理程序数据类型、自定义属性、声明类型和反射类型等,添加或移除事件处理程序。 
        (7)使用PropertyInfo了解属性的名称、数据类型、声明类型、反射类型和只读或可写状态等,获取或设置属性值。 
        (8)使用ParameterInfo了解参数的名称、数据类型、是输入参数还是输出参数,以及参数在方法签名中的位置等。

    反射用到的命名空间:
        System.Reflection
        System.Type
        System.Reflection.Assembly
        
    反射用到的主要类:
        System.Type 类--通过这个类可以访问任何给定数据类型的信息。
        System.Reflection.Assembly类--它可以用于访问给定程序集的信息,或者把这个程序集加载到程序中。
        
    System.Type类:
        System.Type 类对于反射起着核心的作用。但它是一个抽象的基类,Type有与每种数据类型对应的派生类,我们使用这个派生类的对象的方法、字段、属性来查找有关该类型的所有信息。
        获取给定类型的Type引用有3种常用方式:
        ●使用 C# typeof 运算符。
            Type t = typeof(string);
        ●使用对象GetType()方法。
            string s = "grayworm";
            Type t = s.GetType(); 
        ●还可以调用Type类的静态方法GetType()。
            Type t = Type.GetType("System.String");
           
        上面这三类代码都是获取string类型的Type,在取出string类型的Type引用t后,我们就可以通过t来探测string类型的结构了。 
                string n = "grayworm";
                Type t = n.GetType();
                foreach (MemberInfo mi in t.GetMembers())
                {
                    Console.WriteLine("{0}/t{1}",mi.MemberType,mi.Name);
                }
        
        Type类的属性:
            Name 数据类型名
            FullName 数据类型的完全限定名(包括命名空间名)
            Namespace 定义数据类型的命名空间名
            IsAbstract 指示该类型是否是抽象类型
            IsArray   指示该类型是否是数组
            IsClass   指示该类型是否是类
            IsEnum   指示该类型是否是枚举
            IsInterface    指示该类型是否是接口
            IsPublic 指示该类型是否是公有的
            IsSealed 指示该类型是否是密封类
            IsValueType 指示该类型是否是值类型
        Type类的方法:
            GetConstructor(), GetConstructors():返回ConstructorInfo类型,用于取得该类的构造函数的信息
            GetEvent(), GetEvents():返回EventInfo类型,用于取得该类的事件的信息
            GetField(), GetFields():返回FieldInfo类型,用于取得该类的字段(成员变量)的信息
            GetInterface(), GetInterfaces():返回InterfaceInfo类型,用于取得该类实现的接口的信息
            GetMember(), GetMembers():返回MemberInfo类型,用于取得该类的所有成员的信息
            GetMethod(), GetMethods():返回MethodInfo类型,用于取得该类的方法的信息
            GetProperty(), GetProperties():返回PropertyInfo类型,用于取得该类的属性的信息
        可以调用这些成员,其方式是调用Type的InvokeMember()方法,或者调用MethodInfo, PropertyInfo和其他类的Invoke()方法。 

     一些其他的有用的函数

    查看类中的构造方法:
            

            NewClassw nc = new NewClassw();
            Type t = nc.GetType();
            ConstructorInfo[] ci = t.GetConstructors();    //获取类的所有构造函数
            foreach (ConstructorInfo c in ci) //遍历每一个构造函数
            {
                ParameterInfo[] ps = c.GetParameters();    //取出每个构造函数的所有参数
                foreach (ParameterInfo pi in ps)   //遍历并打印所该构造函数的所有参数
                {
                    Console.Write(pi.ParameterType.ToString()+" "+pi.Name+",");
                }
                Console.WriteLine();
            }


        
        用构造函数动态生成对象:
            

           Type t = typeof(NewClassw);
            Type[] pt = new Type[2];
            pt[0] = typeof(string);
            pt[1] = typeof(string);
            //根据参数类型获取构造函数 
            ConstructorInfo ci = t.GetConstructor(pt); 
            //构造Object数组,作为构造函数的输入参数 
            object[] obj = new object[2]{"grayworm","hi.baidu.com/grayworm"};   
            //调用构造函数生成对象 
            object o = ci.Invoke(obj);    
            //调用生成的对象的方法测试是否对象生成成功 
            //((NewClassw)o).show();    


        
        用Activator生成对象:
           

           Type t = typeof(NewClassw);
            //构造函数的参数 
            object[] obj = new object[2] { "grayworm", "hi.baidu.com/grayworm" };   
            //用Activator的CreateInstance静态方法,生成新对象 
            object o = Activator.CreateInstance(t,"grayworm","hi.baidu.com/grayworm"); 
            //((NewClassw)o).show();


        查看类中的属性:
         

            NewClassw nc = new NewClassw();
            Type t = nc.GetType();
            PropertyInfo[] pis = t.GetProperties();
            foreach(PropertyInfo pi in pis)
            {
                Console.WriteLine(pi.Name);
            }
        


        查看类中的public方法:
            

            NewClassw nc = new NewClassw();
            Type t = nc.GetType();
            MethodInfo[] mis = t.GetMethods();
            foreach (MethodInfo mi in mis)
            {
                Console.WriteLine(mi.ReturnType+" "+mi.Name);
            }


        
        查看类中的public字段
           

     NewClassw nc = new NewClassw();
            Type t = nc.GetType();
            FieldInfo[] fis = t.GetFields();
            foreach (FieldInfo fi in fis)
            {
                Console.WriteLine(fi.Name);
            } (http://hi.baidu.com/grayworm)


           
        用反射生成对象,并调用属性、方法和字段进行操作 
           

           NewClassw nc = new NewClassw();
            Type t = nc.GetType();
            object obj = Activator.CreateInstance(t);
            //取得ID字段 
            FieldInfo fi = t.GetField("ID");
            //给ID字段赋值 
            fi.SetValue(obj, "k001");
            //取得MyName属性 
            PropertyInfo pi1 = t.GetProperty("MyName");
            //给MyName属性赋值 
            pi1.SetValue(obj, "grayworm", null);
            PropertyInfo pi2 = t.GetProperty("MyInfo");
            pi2.SetValue(obj, "hi.baidu.com/grayworm", null);
            //取得show方法 
            MethodInfo mi = t.GetMethod("show");
            //调用show方法 
            mi.Invoke(obj, null);


            
    System.Reflection.Assembly类 
         Assembly类可以获得程序集的信息,也可以动态的加载程序集,以及在程序集中查找类型信息,并创建该类型的实例。
        使用Assembly类可以降低程序集之间的耦合,有利于软件结构的合理化。
        
        通过程序集名称返回Assembly对象
            Assembly ass = Assembly.Load("ClassLibrary831");
        通过DLL文件名称返回Assembly对象
            Assembly ass = Assembly.LoadFrom("ClassLibrary831.dll");
        通过Assembly获取程序集中类 
            Type t = ass.GetType("ClassLibrary831.NewClass");   //参数必须是类的全名
        通过Assembly获取程序集中所有的类
            Type[] t = ass.GetTypes();
           
        //通过程序集的名称反射
        

        Assembly ass = Assembly.Load("ClassLibrary831");
        Type t = ass.GetType("ClassLibrary831.NewClass");
        object o = Activator.CreateInstance(t, "grayworm", "http://hi.baidu.com/grayworm");
        MethodInfo mi = t.GetMethod("show");
        mi.Invoke(o, null);

       //通过DLL文件全名反射其中的所有类型
       

     Assembly assembly = Assembly.LoadFrom("xxx.dll的路径");
        Type[] aa = a.GetTypes();
    
        foreach(Type t in aa)
        {
            if(t.FullName == "a.b.c")
            {
                object o = Activator.CreateInstance(t);
            }
        }

    其他关于反射的博客,参考的博客

    (1)https://www.cnblogs.com/vaevvaev/p/6995639.html

    (2)https://www.cnblogs.com/zhang1f/p/11680236.html

    萌橙 你瞅啥?
  • 相关阅读:
    javascript中的screen对象
    javascript的navigator对象
    Javascript的location对象
    javascript 关于闭包的知识点
    微信小程序教程(第三篇)
    微信小程序----关于变量对象data 和 前端wxml取后台js变量值
    微信小程序教程(第四篇)
    微信小程序教程(第二篇)
    微信小程序教程(第一篇)
    操作文件的方法
  • 原文地址:https://www.cnblogs.com/daimaxuejia/p/11982383.html
Copyright © 2011-2022 走看看