C#高级语法笔记 反射

c#反射 

我们创建对象其实就是需要一个类型就可以创建了  所以用反射创建对象的最终需要的就是获得我们想要的类型

using System.Reflection;  //命名空间引用

//核心代码三步走 

//下面为xml配置 方便修改逻辑 可以滤过

string strname = ConfigurationManager.AppSettings["DB.Sqlserver.DBHelper"];
            string[] strnamearray = strname.Split(',');

            //Assembly assembly = Assembly.Load("DB.Sqlserver");


//核心代码第一步 加载dll  传入bin目录下dll名字 

            Assembly assembly = Assembly.Load(strnamearray[1]);

//这些为打印显示 方便理解

            foreach ( Module module in assembly.GetModules())
            {
                Console.WriteLine("Name:{0}",module.FullyQualifiedName);
            }
            foreach (Type type  in assembly.GetTypes())
            {
                Console.WriteLine("Nametype:{0}", type.FullName);

            }


            Console.WriteLine("--------------creat object----------------");


  //核心代码第二步 找出dll中需要的类 等等 类型

            Type dbHelperType = assembly.GetType(strnamearray[0]);

//核心代码第三步 依据类型创建对象  这样对象就创建完毕了

            object dbHelpType = Activator.CreateInstance(dbHelperType);

//下面用反射来调构建出来的dll里的类的方法

下图对照


  MethodInfo Query = dbHelperType.GetMethod("Query");
            Query.Invoke(dbHelpType, null);//无参
            MethodInfo Query2 = dbHelperType.GetMethod("Query2");
            Query2.Invoke(dbHelpType, new object[]{11});//int参
            MethodInfo Query3 = dbHelperType.GetMethod("Query3",new Type[] {typeof(int) });
            Query3.Invoke(dbHelpType, new object[] { 11 });//int参
            MethodInfo Query4 = dbHelperType.GetMethod("Query3", new Type[] { typeof(string) });
            Query4.Invoke(dbHelpType, new object[] {"hahah哈" });//string参  不一一列举了 举一反三
            MethodInfo disshow = dbHelperType.GetMethod("Disshow",BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
            disshow.Invoke(dbHelpType, new object[] { });//最6的来了 访问私有函数 可以破坏单例 哈哈

            Console.WriteLine(dbHelpType.GetType());


end

猜你喜欢

转载自blog.csdn.net/wsxhking/article/details/79935598
今日推荐