反射(Reflection)是.NET中的重要机制,通过反射,可以在运行时获得.NET中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。还可以获得每个成员的名称、限定符和参数等。有了反射,即可对每一个类型了如指掌。如果获得了构造函数的信息,即可直接创建对象,即使这个对象的类型在编译时还不知道。
class Program
{
/// <summary>
/// 创建Mymath类库,包含静态方法Add和非静态方法Abstract,使用loadFile来加载
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//加载程序集
Assembly assem = Assembly.LoadFile(@"D:\我的文档\Visual Studio 2008\Projects\MyMath\MyMath\bin\Debug\MyMath.dll");
Type type = assem.GetType("MyMath.Math");
//利用MethodInfo得到方法的具体信息
MethodInfo method = type.GetMethod("Add");
Console.WriteLine(method.ToString());
//调用静态方法Add
object[] parameters = new object[2];
parameters[0] = 1; parameters[1] = 2;
string result = (string)method.Invoke(null, parameters);
Console.WriteLine("the add result is {0}", result);
//使用非静态方法Abstract
Object obj = assem.CreateInstance("MyMath.Math");
//接着是调用自己指定的Abstract方法
method = type.GetMethod("Abstract");
//传入参数列表和调用的对象
result = (string)method.Invoke(obj, parameters);
Console.WriteLine("the abstract result is {0}", result);
Console.ReadKey();
}
}
namespace MyMath
{
public class Math
{
public static string Add(double num1,double num2)
{
double result = num1 + num2;
return result.ToString();
}
public string Abstract(double num1, double num2)
{
double result = num1 - num2;
return result.ToString();
}
}
}
返回结果:
System.String Add(Double, Double)
the add result is 3
the abstract result is -1