自定义特性

  [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;
            }
        }
    }
}
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);

其他关于反射的博客

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

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

02-10 18:51