1..NET反射的概述 4..NET反射常用类型 使用注意: 5..NET反射示例Demo (2).TestClassLib类库的Arithmetic类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestClassLib { /// <summary> /// 定义示例接口Iwel /// </summary> public interface Iwel { string Print(); } /// <summary> /// 构造测试数据类 /// </summary> public class Arithmetic:Iwel { //定义私有变量 private int numOne; private int numTwo; #region 构造函数测试 //不带参数的构造函数 public Arithmetic() { } //带参数构造函数,初始化numOne和numTwo public Arithmetic(int intNumOne, int intNumTwo) { this.numOne = intNumOne; this.numTwo = intNumTwo; } #endregion #region 属性测试 //公共属性访问NumOne public int NumOne { get { return numOne; } set { numOne = value; } } //公共属性 访问NumTwo public int NumTwo { get { return numTwo; } set { numTwo = value; } } #endregion #region 方法测试 /// <summary> /// 私有非静态不带参数的方法 /// </summary> /// <returns></returns> private string Add() { return "Add()方法是一个私有不带参数的方法"; } /// <summary> /// 私有静态带参数无返回值的方法 /// </summary> /// <param name="intNumOne"></param> private static void Multiplcation(int intNumOne) { Console.WriteLine("Multiplication()方法是一个私有不带参数无返回值的静态方法"); } /// <summary> /// 私有非静态带参数的方法 /// </summary> /// <param name="intNumOne"></param> /// <param name="intNumTwo"></param> private void Subtration(int intNumOne, int intNumTwo) { string strMeesage = "{0}-{1}={2} Subtration(int intNumOne, int intNumTwo)方法是一个私有带参数的方法"; Console.WriteLine(strMeesage, intNumOne, intNumTwo, intNumOne - intNumTwo); } /// <summary> /// 公有非静态不带参数的方法 /// </summary> /// <returns></returns> public void Write() { Console.WriteLine( "Write() 是一个共有的不带参数无返回值的方法"); } /// <summary> /// 公有静态带参数的方法 /// </summary> /// <param name="intNumOne"></param> /// <param name="intNumTwo"></param> public static string Multiplcation(int intNumOne, int intNumTwo) { string strMessage = "{0}*{1}={2} Multiplcation(int intNumOne,int intNumTwo)方法是一个公有的静态带参数的方法"; strMessage = string.Format("{0}*{1}={2}", intNumOne, intNumTwo, intNumOne * intNumTwo); return strMessage; } /// <summary> /// 公有非静态带参数的方法 /// </summary> /// <param name="intNumOne"></param> /// <param name="intNumTwo"></param> /// <returns></returns> public string Add(int intNumOne,int intNumTwo) { string strMessage = string.Format("{0}+{1}={2}", intNumOne, intNumTwo, intNumOne + intNumTwo); return strMessage; } #endregion /// <summary> /// 集成接口方法 /// </summary> /// <returns></returns> public string Print() { return " Print() 继承接口方法"; } } } (3).TestClassLib类库的TestClass类
View Code
(4).TestClassLib类库的DialogInvoker类
View Code
(5).TestClassLib类库的TestDialog类
View Code
(6).ReflectTest的Program.cs代码调用测试 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using TestClassLib; namespace ReflectTest { class Program { //定义委托测试 delegate void TestDelegate(int intNumOne,int intNumTwo); static void Main(string[] args) { SimpleTest();//简单测试 TestArithmetic();//分析测试 TestDialog();//模拟测试 Console.ReadLine(); } /// <summary> /// 基本简单测试 /// </summary> static void SimpleTest() { //System.Reflection.Assembly ass = Assembly.Load("TestClassLib"); //加载DLL //System.Type t = ass.GetType("TestClassLib.TestChildrenClass");//获得类型 string path = "TestClassLib.TestClass" + "," + "TestClassLib";//命名空间.类型名,程序集 Type testType = Type.GetType(path);//加载类型 object objType = System.Activator.CreateInstance(testType);//创建实例 System.Reflection.MethodInfo methodReflection = testType.GetMethod("TestMethod");//获得方法 object str = methodReflection.Invoke(objType, new object[] { "MM" });//调用方法 Console.WriteLine("简单测试输出:"+str.ToString()); } /// <summary> /// 反射分析测试 /// </summary> static void TestArithmetic() { string strAssembly = "TestClassLib";//程序集DLL string strReflectClass = "TestClassLib.Arithmetic";//命名空间.类型 string strMethodAdd = "Add";//调用方法Add名称 string strMethodWrite = "Write";//调用方法Write名称 string strMethodMul = "Multiplcation";//调用方法Multiplcation名称 Assembly AssTestClassLib = Assembly.Load(strAssembly);//得到程序集 Type ArithmeticClass = AssTestClassLib.GetType(strReflectClass);;//得到具体类型 //Type ArithmeticClass = Type.GetType(strReflectClass + "," + strAssembly);//创建对象也可以使用:命名空间.类型名,程序集 #region 获取程序集下的信息 Console.WriteLine("\n得到"+strAssembly+"中所有类:" ); foreach (Type type in AssTestClassLib.GetTypes()) { Console.WriteLine(type.Name+"是"+strAssembly+"命名空间下的对象"); } Console.WriteLine("\n得到"+strAssembly+".dll中的模块集:"); Module[] modules = AssTestClassLib.GetModules(); foreach (Module module in modules) { Console.WriteLine(module.Name+"是"+strAssembly+"下的模块集"); } #endregion #region 获取指定类下的信息 Console.WriteLine("\n具体类型是"+ArithmeticClass.Name); Console.WriteLine("{0}是不是Public类型{1}",ArithmeticClass,ArithmeticClass.IsPublic); Console.WriteLine("{0}是不是Privet类型{1}",ArithmeticClass,ArithmeticClass.IsPrimitive); Console.WriteLine("\n得到" + ArithmeticClass + "类下的构造函数:"); ConstructorInfo [] constructorInfos = ArithmeticClass.GetConstructors(); foreach (ConstructorInfo constructor in constructorInfos) { Console.WriteLine(constructor); } Console.WriteLine("\n得到"+ArithmeticClass+"类下的所有属性:"); PropertyInfo[] propertyInfos = ArithmeticClass.GetProperties(); foreach (PropertyInfo prop in propertyInfos) { Console.WriteLine(prop.Name+"是"+ArithmeticClass + "类下的属性"); } Console.WriteLine("\n得到"+ArithmeticClass+"类下所有的接口:"); Type[] typeInterfaces = ArithmeticClass.GetInterfaces(); foreach (Type typeInterface in typeInterfaces) { Console.WriteLine(typeInterface.Name+"是"+ArithmeticClass+"类下的接口"); } #region 获取所有方法的信息 Console.WriteLine("\n得到"+ArithmeticClass+"类下所有方法:"); //查找私有方法 MethodInfo[] methodPrivates = ArithmeticClass.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic); foreach (MethodInfo method in methodPrivates) { Console.WriteLine("私有方法 方法名称:{0} 方法信息:{1}",method.Name,method); } //查找公有方法 MethodInfo[] methodPublics = ArithmeticClass.GetMethods(BindingFlags.Instance | BindingFlags.Public); foreach (MethodInfo method in methodPublics) { Console.WriteLine("公有方法 方法名称:{0} 方法信息:{1}", method.Name, method); } //查找私有静态方法 MethodInfo[] methodStaticPrivates = ArithmeticClass.GetMethods(BindingFlags.NonPublic | BindingFlags.Static); foreach (MethodInfo method in methodStaticPrivates) { Console.WriteLine("私有静态方法 方法名称:{0} 方法信息:{1}", method.Name, method); } //查找公有静态方法 MethodInfo[] methodStaticPublics = ArithmeticClass.GetMethods(BindingFlags.Public | BindingFlags.Static); foreach (MethodInfo method in methodPrivates) { Console.WriteLine("公有静态方法 方法名称:{0} 方法信息:{1}", method.Name, method); } #endregion #endregion #region 创建对象实例 Console.WriteLine("\n创建对象实例:"); int num1 = 3, num2 = 5;//定义参数 //创建一个不带参数的实例 object obj = Activator.CreateInstance(ArithmeticClass, null); //公有非静态带参数和返回值的方法调用 MethodInfo methodAdd = ArithmeticClass.GetMethod(strMethodAdd); object[] addParams = new object[] {num1,num2 }; string strReturnAdd=methodAdd.Invoke(obj, addParams).ToString(); Console.WriteLine("创建{0}类,调用公有非静态{1}方法,传入参数{2}和{3},返回值:{4}",ArithmeticClass, strMethodAdd, num1, num2, strReturnAdd); //私有非静态无参无返回值方法调用 MethodInfo methodStaticAdd = ArithmeticClass.GetMethod(strMethodAdd, BindingFlags.Instance | BindingFlags.NonPublic); string strStaticAdd=methodStaticAdd.Invoke(obj,null).ToString(); Console.WriteLine("创建{0}类,调用私有非静态{1}方法,返回值:{2}:", ArithmeticClass, strMethodAdd, strStaticAdd); //公有非静态无参数无返回值方法调用 MethodInfo methodWite = ArithmeticClass.GetMethod(strMethodWrite, BindingFlags.Instance | BindingFlags.Public); Console.WriteLine("创建{0}类,调用公有非静态{1}方法,无参数无返回值:", ArithmeticClass, strMethodWrite, methodWite.Invoke(obj, null)); //公有静态带参数有返回值的方法调用 MethodInfo methodMultiplcation = ArithmeticClass.GetMethod(strMethodMul, BindingFlags.Public | BindingFlags.Static); object[] multParams = new object[] { num1, num2 }; string multReturn = methodMultiplcation.Invoke(obj, multParams).ToString(); //string multReturn = methodMultiplcation.Invoke(null, multParams).ToString();//调用静态方法也可以转入null对象 Console.WriteLine("创建{0}类,调用公有静态{1}方法,传入参数{2}和{3},返回值:{4}", ArithmeticClass, strMethodMul, num1, num2, multReturn); //测试InvokeMember方法 object objReturn= ArithmeticClass.InvokeMember(strMethodAdd, BindingFlags.InvokeMethod, null, obj,new object[]{num1,num2}); Console.WriteLine("测试InvokeMember方法:创建{0}类,调用公有静态{1}方法,传入参数{2}和{3},返回值:{4}:" , ArithmeticClass, strMethodAdd, num1, num2, objReturn.ToString()); #endregion //动态创建委托 Console.WriteLine("\n动态创建委托:"); TestDelegate testDel = (TestDelegate)Delegate.CreateDelegate(typeof(TestDelegate), obj, "Subtration"); testDel(9,3); } /// <summary> /// 模拟测试 /// </summary> static void TestDialog() { string strAssembly = "TestClassLib";//程序集DLL string strDialogReflect = "TestClassLib.TestDialog"; string strDialogInvokerReflect = "TestClassLib.DialogInvoker"; string strDialogNestedTypeReflect = "TestClassLib.TestClass";//嵌套如何关系类,命名空间.类 string strNestedType = "Dialog";//嵌套组合类 string strDialogMethod = "OnInit"; string strDialogInvokerMethod = "RegisterWithKey"; Console.WriteLine("\n模拟测试:"); Assembly assemblyTest = Assembly.Load(strAssembly); //间接调用 Type typeDialog = assemblyTest.GetType(strDialogReflect); object objDialog = Activator.CreateInstance(typeDialog); MethodInfo methodDialog = typeDialog.GetMethod(strDialogMethod); methodDialog.Invoke(objDialog, null); //直接调用 Type typeDialogInvoker = assemblyTest.GetType(strDialogInvokerReflect); object objDialogInvoker = Activator.CreateInstance(typeDialogInvoker); MethodInfo methodDialogInvoker = typeDialogInvoker.GetMethod(strDialogInvokerMethod); methodDialogInvoker.Invoke(objDialogInvoker, new object[] { "MM", "KK" }); //使用嵌套组合关系调用(这个更实用) var typeTestClass =assemblyTest.GetType(strDialogNestedTypeReflect); //var typeTestClass = Assembly.GetExecutingAssembly().GetType(strDialogNestedTypeReflect);//如果在同一个程序集下可以使用这种方式 var testClass= Activator.CreateInstance(typeTestClass);//创建本类 var typeNestedDialog= typeTestClass.GetNestedType(strNestedType);//获取嵌套组合类 var dialogClass = Activator.CreateInstance(typeNestedDialog);//创建嵌套组合类 var methodInfo = dialogClass.GetType().GetMethod(strDialogInvokerMethod, BindingFlags.Instance | BindingFlags.Public); methodInfo.Invoke(dialogClass, new object[] {"TT","KK" }); } } } 6.运行效果如下: 7.反射实现工厂模式 public partial class 反射 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string typeName = typeof(TestClass).AssemblyQualifiedName; ITestInterface iface = RawGenericFactory.Create<ITestInterface>(typeName); string result = iface.doSomething(); Response.Write(result); } } public static class RawGenericFactory { public static T Create<T>(string typeName) { //Activator.CreateInstance 反射 根据程序集创建借口或者类 //Type.GetType() 根据名称获得程序集信息 //typeof(ConcertProduct).AssemblyQualifiedName //_iproduct.GetType().AssemblyQualifiedName return (T)Activator.CreateInstance(Type.GetType(typeName)); } } public interface ITestInterface { string doSomething(); } public class TestClass : ITestInterface { public int Id { get; set; } public override string ToString() { return Id.ToString(); } public string doSomething() { return "ok"; } }
8.反射实现自定义ORM框架 [Orm.Table("TestORM")] public class TestORM { [Orm.Colum("Id",DbType.Int32)] public int Id { get; set; } [Orm.Colum("UserName", DbType.String)] public string UserName { get; set; } [Orm.Colum("Password", DbType.String)] public string Password { get; set; } [Orm.Colum("CreatedTime", DbType.DateTime)] public DateTime CreatedTime { get; set; } } protected void Button3_Click(object sender, EventArgs e) { TestORM t = new TestORM() { Id=1, UserName="binfire", Password="xxx", CreatedTime=DateTime.Now }; Orm.OrmHelp h=new Orm.OrmHelp(); h.Insert(t); } namespace Orm { [AttributeUsageAttribute(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public class TableAttribute : Attribute { //保存表名的字段 private string _tableName; public TableAttribute() { } public TableAttribute(string tableName) { this._tableName = tableName; } /// /// 映射的表名(表的全名:模式名.表名) /// public string TableName { set { this._tableName = value; } get { return this._tableName; } } } [AttributeUsageAttribute(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public class ColumAttribute : Attribute { private string _columName; private DbType _dbType; public ColumAttribute() { } public ColumAttribute(string columName) : this() { this._columName = columName; } public ColumAttribute(string columName, DbType dbType) : this(columName) { this._dbType = dbType; } //列名 public virtual string ColumName { set { this._columName = value; } get { return this._columName; } } //描述一些特殊的数据库类型 public DbType DbType { get { return _dbType; } set { _dbType = value; } } } public class OrmHelp { public void Insert(object table) { Type type = table.GetType(); //定义一个字典来存放表中字段和值的对应序列 Dictionary<string,string> columValue = new Dictionary<string,string>(); StringBuilder SqlStr = new StringBuilder(); SqlStr.Append("insert into "); //得到表名子 TableAttribute temp = (TableAttribute)type.GetCustomAttributes(typeof(TableAttribute), false).First(); SqlStr.Append(temp.TableName); SqlStr.Append("("); PropertyInfo[] Propertys = type.GetProperties(); foreach (var item in Propertys) { object[] attributes = item.GetCustomAttributes(false); foreach (var item1 in attributes) { //获得相应属性的值 string value = table.GetType().InvokeMember(item.Name, System.Reflection.BindingFlags.GetProperty, null, table, null).ToString(); ColumAttribute colum = item1 as ColumAttribute; if (colum != null) { columValue.Add(colum.ColumName, value); } } } //拼插入操作字符串 foreach (var item in columValue) { SqlStr.Append(item.Key); SqlStr.Append(","); } SqlStr.Remove(SqlStr.Length - 1, 1); SqlStr.Append(") values('"); foreach (var item in columValue) { SqlStr.Append(item.Value); SqlStr.Append("','"); } SqlStr.Remove(SqlStr.Length - 2, 2); SqlStr.Append(")"); HttpContext.Current.Response.Write(SqlStr.ToString()); } } }
参考博客:《 .NET中反射机制的使用与分析 》《 利用反射动态创建对象 》《C#反射机制》 |
|
来自: ThinkTank_引擎 > 《反射-权限》