记录一个用到的反射实现方式,有时会突然忘掉,正好写一篇博客,加深下印象。
反射用到的命名空间:
System.Reflection
System.Type
System.Reflection.Assembly
反射的用途:
(1)使用程序集定义和加载程序集,加载在程序集清单中列出模块,以及从此程序集中查找类型并创建该类型的实例。
(2)使用模块了解包含模块的程序集以及模块中的类等,还可以获取在模块上定义的所有全局方法或其他特定的非全局方法。
(3)使用ConstructorInfo了解构造函数的名称,参数,访问修饰符(如pulic或private)和实现详细信息(如abstract或virtual)等。
(4)使用MethodInfo了解方法的名称,返回类型,参数,访问修饰符(如pulic或private)和实现详细信息(如abstract或virtual)等。
(5)使用FiedInfo了解字段的名称,访问修饰符(如public或private)和实现详细信息(如静态)等,并获取或设置字段值。
(6)使用EventInfo了解事件的名称,事件处理程序数据类型,自定义属性,声明类型和反射类型等,添加或移除事件处理程序。
(7 )使用的PropertyInfo了解属性的名称,数据类型,声明类型,反射类型和只读或可写状态等,获取或设置属性值。
(8)使用的ParameterInfo了解参数的名称,数据类型,是输入参数还是输出参数,以及参数在方法签名中的位置等。
下面这是Assembly(反射)的一个实现案例,可以放在C#的控制台Main方法里测试,也可以构建一个方法。
//1、获取指定路径的程序集对象
Assembly assembly = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "CalculatorTest.dll"));
//2、根据程序集对象和 类型名称创建对象,并且可以传递构造参数,然后可以用 objAny.GetType() 获取 Type
object jiafaObj = assembly.CreateObject("CalculatorTest.JiaFaClass", 3, 4);
if (jiafaObj != null)
{
Type objType = jiafaObj.GetType();
#region 第二种方式 创建Type和Type的object
2、根据程序集对象和 命名空间.类全名 创建类型
//Type objType = assembly.GetType("CalculatorDll.JiaFaClass");
2.1、根据类型创建 类型的实例
//object jiafaObj = Activator.CreateInstance(objType);
2.2、构造函数方式赋值
//ConstructorInfo ctor = objType.GetConstructor(new Type[] { typeof(double), typeof(double) });
//ctor.Invoke(jiafaObj, new object[] { 3, 4 });
#region 通过 属性或字段方式 而不是 在构造函数中 传值
2.2属性方式赋值
//PropertyInfo num1 = calculatorType.GetProperty("Number1");
//PropertyInfo num2 = calculatorType.GetProperty("Number2");
//if (num1 != null && num2 != null)
//{
// num1.SetValue(obj, 3, null);
// num2.SetValue(obj, 4, null);
//}
2.2字段方式赋值
//FieldInfo num1 = calculatorType.GetField("number1");
//FieldInfo num2 = calculatorType.GetField("number1");
//if (num1 != null && num2 != null)
//{
// num1.SetValue(obj, 3);
// num2.SetValue(obj, 4);
//}
#endregion
#endregion
//3、根据函数名称创建方法元数据
MethodInfo jiSuanMethod = objType.GetMethod("JiSuan");
if (jiSuanMethod!=null)
{
//4、执行函数,以及获取函数返回值
object jiSuanReturn = jiSuanMethod.Invoke(jiafaObj, new object[] { }); //没参数用new object[] {}或 null 有参数用 new object[] {1,"str"} 这样
Console.WriteLine(jiSuanReturn.ToString());
}
}
Console.ReadKey();
下面是上面方法用到的CalculatorTest.dll程序集文件的具体代码,只需要新建一个CalculatorTest类库,新建一个JiaFaClass类将下面代码复制到里面,就可以测试了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CalculatorTest
{
class JiaFaClass
{
public JiaFaClass(double num1,double num2)
{
this.number1 = num1;
this.number2 = num2;
}
private double number1;
private double number2;
public double Number1 { get { return number1; } set { number1 = value; } }
public double Number2 { get { return number2; } set { number2 = value; } }
public double JiSuan()
{
return number1 + number2;
}
}
}
下面是一些其它的博客资料可以参考:
详解C#的中反射 https://www.cnblogs.com/Stephenchao/p/4481995.html
C#反射(反射)详解 https://www.cnblogs.com/wangshenhe/p/3256657.html
C#反射(反射) http://www.runoob.com/csharp/csharp-reflection.html