通过反射(Reflection)可以在运行时获得.Net中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。
有了反射,只要获得了构造函数的信息,就可以直接创建对象。
一些在反射中经常使用的类
Assembly类,可以使用Assembly.Load和Assembly.LoadFrom方法动态地加载程序集。
Type类,System.Type类是一个抽象类,代表公用类型系统中的一种类型。
Activator类,可以通过CreateComInstanceFrom、CreateInstance、CreateInstanceFrom、GetObject四个静态方法加载COM对象或者程序集,并能够创建指定类型的实例。
例子
先创建一个类库项目ClassLibrary1.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClassLibrary1
{
public class ClassPerson
{
public ClassPerson()
: this(null)
{ }
public ClassPerson(string strname)
{
name = strname;
}
private string name = null;
private string sex;
private int age;
public string Name
{
set { name = value; }
get {return name;}
}
public string Sex
{
set { sex = value; }
get { return sex; }
}
public int Age
{
set { age = value; }
get { return age; }
}
public void SayHello()
{
if (name == null)
{
System.Console.WriteLine("Hello World");
}
else
{
System.Console.WriteLine("Hello"+name);
}
}
}
}
编译后会自动生成一个ClassLibrary1.dll文件,下面在通过反射来获取ClassLibrary1.dll中对象的信息。
首先,添加Using System.Reflection的命名空间的引用,然后将ClassLibrary1.dll复杂到控制台应用程序集(bin\Debug)目录下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("列出程序集中的所有类型");
Assembly ass = Assembly.LoadFrom("ClassLibrary1.dll");
Type classPerson = null;
Type[] mytypes = ass.GetTypes();
foreach (Type t in mytypes)
{
Console.WriteLine(t.Name);
if (t.Name == "ClassPerson")
{
classPerson = t;
}
}
Console.WriteLine("列出ClassPerson类中所有的方法");
MethodInfo[] mif = classPerson.GetMethods();
foreach (MethodInfo mf in mif)
{
Console.WriteLine(mf.Name);
}
Console.WriteLine("实例化ClassPerson,并调用SayHello方法");
object obj = Activator.CreateInstance(classPerson);
object objName = Activator.CreateInstance(classPerson, " yelinghui");
MethodInfo msayhello = classPerson.GetMethod("SayHello");
msayhello.Invoke(obj, null);
msayhello.Invoke(objName, null);
Console.ReadLine();
}
}
}
注:msayhello.Invoke(obj, null)是空参数的实力构造
msayhello.Invoke(objName, null)是带参数的实力构造