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