1. 程式人生 > >C# 反射Reflection——反射反射程序員的快樂

C# 反射Reflection——反射反射程序員的快樂

*** 文件夾 指定字段 完整路徑 eric mea write adf getc

一、什麽是反射 反射Reflection:System.Reflection,是.Net Framework提供的一個幫助類庫,可以讀取並使用metadata。 反射是無處不在的,MVC-Asp.Net-ORM-IOC-AOP 幾乎所有的框架都離不開反射 如下圖是程序執行的過程,高級語言經過編譯器編譯得到dll/exe文件,這裏的文件可以跨平臺使用,編譯後的文件中其實包括了metadata元數據(數據清單,描述了DLL/exe裏面的各種信息)和IL(也是一種面向對象語言,但是不太好閱讀)在經過CLR/JIT編譯得到可以被計算機所執行的機器碼。 技術分享圖片 二、反射的使用 一)反射動態加載程序集 技術分享圖片
            Assembly assembly1 = Assembly.LoadFrom(@"DB.MySql.dll");//當前路徑
            Assembly assembly2 = Assembly.LoadFile(@"D:\ruanmou\MyReflection\bin\Debug\DB.MySql.dll");//dll、exe文件完整路徑
            Assembly assembly3 = Assembly.Load(@"DB.MySql");//dll、exe名稱   dll/exe需要拷貝至程序bin文件夾下
View Code

二)簡單工廠生產對應實體

技術分享圖片
        /// <summary>
        /// 簡單工廠生產對應實體
        /// </summary>
        /// <returns></returns>
        public static T CreateInstance<T>()
        {
            Assembly assembly = Assembly.Load(ConfigurationManager.AppSettings["DalDllName"]);//加載dll
            Type dalType = assembly.GetType(ConfigurationManager.AppSettings["
DalTypeName"]);//獲取類型 return (T)Activator.CreateInstance(dalType);//創建對象 //var newType = dalType.MakeGenericType(typeof(T));//獲取泛型類型 //return (T)Activator.CreateInstance(newType);創建泛型類型對象 }
View Code

三)常用方法

技術分享圖片
            Type[] types= assembly.GetTypes();//獲取程序集所有類型
            Type type= assembly.GetType("TypeName");//獲取指定類型
            MethodInfo[] methods= type.GetMethods();//獲取所有方法
            MethodInfo method= type.GetMethod("methodName");//獲取指定方法
            PropertyInfo[] propertys= type.GetProperties();//獲取所有屬性
            PropertyInfo property = type.GetProperty("propertyName");//獲取指定屬性
            FieldInfo[] fields= type.GetFields();//獲取所有字段
            FieldInfo field = type.GetField("fieldName");//獲取指定字段
            Attribute attribute = type.GetCustomAttribute(typeof(DisplayNameAttribute));//獲取指定特性
View Code

反射調用多參數構造函數,方法

技術分享圖片
    /// <summary>
    /// 反射測試類
    /// </summary>
    public class ReflectionTest
    {
        #region Identity
        /// <summary>
        /// 無參構造函數
        /// </summary>
        public ReflectionTest()
        {
            Console.WriteLine("這裏是{0}無參數構造函數", this.GetType());
        }

        /// <summary>
        /// 帶參數構造函數
        /// </summary>
        /// <param name="name"></param>
        public ReflectionTest(string name)
        {
            Console.WriteLine("這裏是{0} 有參數構造函數", this.GetType());
        }

        public ReflectionTest(int id)
        {
            Console.WriteLine("這裏是{0} 有參數構造函數", this.GetType());
        }
        #endregion

        #region Method
        /// <summary>
        /// 無參方法
        /// </summary>
        public void Show1()
        {
            Console.WriteLine("這裏是{0}的Show1", this.GetType());
        }
        /// <summary>
        /// 有參數方法
        /// </summary>
        /// <param name="id"></param>
        public void Show2(int id)
        {

            Console.WriteLine("這裏是{0}的Show2", this.GetType());
        }
        /// <summary>
        /// 重載方法之一
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        public void Show3(int id, string name)
        {
            Console.WriteLine("這裏是{0}的Show3", this.GetType());
        }
        /// <summary>
        /// 重載方法之二
        /// </summary>
        /// <param name="name"></param>
        /// <param name="id"></param>
        public void Show3(string name, int id)
        {
            Console.WriteLine("這裏是{0}的Show3_2", this.GetType());
        }
        /// <summary>
        /// 重載方法之三
        /// </summary>
        /// <param name="id"></param>
        public void Show3(int id)
        {

            Console.WriteLine("這裏是{0}的Show3_3", this.GetType());
        }
        /// <summary>
        /// 重載方法之四
        /// </summary>
        /// <param name="name"></param>
        public void Show3(string name)
        {

            Console.WriteLine("這裏是{0}的Show3_4", this.GetType());
        }
        /// <summary>
        /// 重載方法之五
        /// </summary>
        public void Show3()
        {

            Console.WriteLine("這裏是{0}的Show3_1", this.GetType());
        }
        /// <summary>
        /// 私有方法
        /// </summary>
        /// <param name="name"></param>
        private void Show4(string name)
        {
            Console.WriteLine("這裏是{0}的Show4", this.GetType());
        }
        /// <summary>
        /// 靜態方法
        /// </summary>
        /// <param name="name"></param>
        public static void Show5(string name)
        {
            Console.WriteLine("這裏是{0}的Show5", typeof(ReflectionTest));
        }
        #endregion
    }
View Code 技術分享圖片
                Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                Type type = assembly.GetType("Ruanmou.DB.SqlServer.ReflectionTest");
                object oTest = Activator.CreateInstance(type);//反射調用無參數構造函數
                object oTest2 = Activator.CreateInstance(type, new object[] { 123 });//反射調用一個int類型參數構造函數
                foreach (var method in type.GetMethods())
                {
                    Console.WriteLine(method.Name);
                    foreach (var parameter in method.GetParameters())//獲取方法參數
                    {
                        Console.WriteLine($"{parameter.Name}  {parameter.ParameterType}");
                    }
                }
                {
                    ReflectionTest reflection = new ReflectionTest();
                    reflection.Show1();
                }
                {
                    MethodInfo method = type.GetMethod("Show1");
                    //if()
                    method.Invoke(oTest, null);//oTest調用無參數方法
                }
                {
                    MethodInfo method = type.GetMethod("Show2");
                    method.Invoke(oTest, new object[] { 123 });//oTest調用一個int類型參數方法
                }
                {
                    MethodInfo method = type.GetMethod("Show3", new Type[] { });
                    method.Invoke(oTest, null);//oTest調用無參數重載方法
                }
                {
                    MethodInfo method = type.GetMethod("Show3", new Type[] { typeof(int) });
                    method.Invoke(oTest, new object[] { 123 });//oTest調用一個int類型參數重載方法
                }
                
                {
                    MethodInfo method = type.GetMethod("Show5");
                    method.Invoke(oTest, new object[] { "String" });//靜態方法實例可以要
                }
                {
                    MethodInfo method = type.GetMethod("Show5");
                    method.Invoke(null, new object[] { "string" });//靜態方法實例也可以不要
                }
View Code 技術分享圖片
                    var method = type.GetMethod("Show4", BindingFlags.Instance | BindingFlags.NonPublic);
                    method.Invoke(oTest, new object[] { "私有方法" });
反射調用私有方法

反射調用泛型方法、泛型類

技術分享圖片
    public class GenericClass<T, W, X>
    {
        public void Show(T t, W w, X x)
        {
            Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
        }
    }

    public class GenericMethod
    {
        public void Show<T, W, X>(T t, W w, X x)
        {
            Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
        }
    }

    public class GenericDouble<T>
    {
        public void Show<W, X>(T t, W w, X x)
        {
            Console.WriteLine("t.type={0},w.type={1},x.type={2}", t.GetType().Name, w.GetType().Name, x.GetType().Name);
        }
    }
View Code 技術分享圖片
               {
                    Console.WriteLine("********************GenericMethod********************");
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.GenericMethod");
                    object oGeneric = Activator.CreateInstance(type);
                    //foreach (var item in type.GetMethods())
                    //{
                    //    Console.WriteLine(item.Name);
                    //}
                    MethodInfo method = type.GetMethod("Show");
                    var methodNew = method.MakeGenericMethod(new Type[] { typeof(int), typeof(string), typeof(DateTime) });
                    object oReturn = methodNew.Invoke(oGeneric, new object[] { 123, "test", DateTime.Now });
                }
                {
                    Console.WriteLine("********************GenericMethod+GenericClass********************");
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.GenericDouble`1").MakeGenericType(typeof(int));
                    object oObject = Activator.CreateInstance(type);
                    MethodInfo method = type.GetMethod("Show").MakeGenericMethod(typeof(string), typeof(DateTime));
                    method.Invoke(oObject, new object[] { 345, "teat", DateTime.Now });

                }
View Code

反射破壞單例

技術分享圖片
    /// <summary>
    /// 單例模式:類,能保證在整個進程中只有一個實例
    /// </summary>
    public sealed class Singleton
    {
        private static Singleton _Singleton = null;
        private Singleton()
        {
            Console.WriteLine("Singleton被構造");
        }

        static Singleton()
        {
            _Singleton = new Singleton();
        }

        public static Singleton GetInstance()
        {
            return _Singleton;
        }
    }
View Code 技術分享圖片
                  {

                    Console.WriteLine("********************Singleton********************");
                    Singleton singleton1 = Singleton.GetInstance(); //new Singleton();
                    Singleton singleton2 = Singleton.GetInstance();
                    Singleton singleton3 = Singleton.GetInstance();
                    Singleton singleton4 = Singleton.GetInstance();
                    Singleton singleton5 = Singleton.GetInstance();
                    Console.WriteLine($"{object.ReferenceEquals(singleton1, singleton5)}");

                    //反射破壞單例---就是發射調用私有構造函數
                    Assembly assembly = Assembly.Load("Ruanmou.DB.SqlServer");
                    Type type = assembly.GetType("Ruanmou.DB.SqlServer.Singleton");
                    Singleton singletonA = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonB = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonC = (Singleton)Activator.CreateInstance(type, true);
                    Singleton singletonD = (Singleton)Activator.CreateInstance(type, true);
                    Console.WriteLine($"{object.ReferenceEquals(singletonA, singletonD)}");
                }
View Code

C# 反射Reflection——反射反射程序員的快樂