C#_反射機制

         反射(Reflection)有下列用途:

  • 它允許在運行時查看特性(attribute)信息。
  • 它允許審查集合中的各種類型,以及實例化這些類型。
  • 它允許延遲綁定的方法和屬性(property)。
  • 它允許在運行時創建新類型,然後使用這些類型執行一些任務。

1.查看特性:

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.MemberInfo info = typeof(Test);
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length;i++ )
            {
                DebugInfo debuginfo = (DebugInfo)attributes[i];
                Console.WriteLine("Develper:{0}\nDate:{1}\nMessage:{2}"
                    ,debuginfo.Developer,debuginfo.Date,debuginfo.Message);
            }
            Console.ReadKey();

        }
    }
    [AttributeUsage(AttributeTargets.Class)]
    public class DebugInfo:Attribute    //自定義特性
    {
        private string developer;
        private string date;
        private string message;

        public string Developer { get { return developer; } }
        public string Date { get { return date; } }
        public string Message { get { return message; } }
        public DebugInfo(string de,string da,string me)
        {
            this.developer = de;
            this.date = da;
            this.message = me;
        }
    }
    [DebugInfo("menghan","2018/4/8","這是一個測試用例")]
    public class Test
    {
        
    }}

2.獲取類型信息

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Type type = typeof(Test1);
            Console.WriteLine("類名:{0}\n類全名:{1}\n命名空間:{2}\n程序集:{3}\n模塊:{4}\n基類:{5}\n類的公共成員",
                type.Name, type.FullName, type.Namespace, type.Assembly, type.Module, type.BaseType);
            MemberInfo[] memberInfos = type.GetMembers();//得到所有公共成員
            foreach(var m in memberInfos)
            {
                Console.WriteLine("{0}:{1}", m.MemberType, m);
            }
            Console.ReadKey();
        }
    }

    public class Test1
    {
        public string member;
        public void Mathod() { }
        public int Property { get; set; }
    }}

3.反射調用方法、屬性

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            System.Reflection.Assembly ass = Assembly.LoadFrom(@"C:\Users\Administrator\documents\visual studio 2013\Projects\test\test\bin\Debug\test.exe"); //加載DLL
            System.Type t = ass.GetType("test.Test1");//獲得類型

            string name = typeof(Test1).AssemblyQualifiedName;
            System.Type t1 = Type.GetType(name);
            System.Type t2 = typeof(Test1);

            object o = System.Activator.CreateInstance(t);//創建實例
            Test1 test1 = (Test1)o; test1.Mathod("測試反射機制");
            System.Reflection.MethodInfo mi = t.GetMethod("Mathod");//獲得方法(只能獲得公共方法)
            mi.Invoke(o, new object[] { "alert('測試反射機制')" });//調用方法
            System.Reflection.PropertyInfo pi = t.GetProperty("Property");
            pi.SetValue(o, 1000);//設置屬性
            Console.WriteLine("屬性:" + pi.GetValue(o));//獲得屬性
            Console.ReadKey();
        }
    }

    public class Test1
    {
        public string member;
        public void Mathod(string message) {
            Console.WriteLine(message);
        }
        public int Property { get; set; }
    }}

4.利用反射實現工廠模式

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            string typename = typeof(Test2).AssemblyQualifiedName;
            ITest itest = TestFactory.Create<Test2>(typename);
            itest.DoSomething();
            Console.ReadKey();
        }
    }
    public static class TestFactory
    {
        public static T Create<T>(string typename)
        {
            return (T)Activator.CreateInstance(Type.GetType(typename));
        }
    }
    public interface ITest
    {
        void DoSomething();
    }
    public class Test2:ITest
    {
        public void DoSomething()
        {
            Console.WriteLine("測試用例");
        }
    }}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章