c#中用反射的方式实例化对象

定义一个类:
namespace Example
{
public class ExampleClass
{
 public int iID = 0;
 public string strName = "";
 public ExampleClass()
 {
  iID = 1;
  strName = "Example"; 
 }

 public ExampleClass(int ID,string Name)
 {
  iID = ID;
  strName = Name; 
 }
}
}


实例化对象:需要引用 useing System.Reflection;
//通过类名获取类的类型
Type tp = Type.GetType("Example.ExampleClass");  //需要带上名字空间

//不带参数的情况--------------------
//获取类的初始化参数信息
ConstructorInfo ct1 = tp.GetConstructor(System.Type.EmptyTypes);
//调用不带参数的构造器
ExampleClass Ex1 = (ExampleClass)ct1.Invoke(null);
MessageBox.Show("ID = " + Ex1.iID.ToString() + "; Name = " + Ex1.strName);
//将输出: ID = 1; Name = Example

//带参数的情况
//定义参数类型数组
Type[] tps = new Type[2];
tps[0] = typeof(int);
tps[1] = typeof(string);
//获取类的初始化参数信息
ConstructorInfo ct2 = tp.GetConstructor(tps);

//定义参数数组
object[] obj = new object[2];
obj[0] = (object)100;
obj[1] = (object)"Param Example";

//调用带参数的构造器
ExampleClass Ex2 = (ExampleClass)ct2.Invoke(obj);
MessageBox.Show("ID = " + Ex2.iID.ToString() + "; Name = " + Ex2.strName);
//将输出: ID = 100; Name = Param Example

转自:http://imay.blog.bokee.net/bloggermodule/blog_printEntry.do?id=503644

你可能感兴趣的:(C#)