获得实例的方法
1.获得同一程序集内的类型的实例。
无参数构造函数
Type t = Type.GetType("AppCode.Employe");
if (t == null)
{
textBox1.Text = "Create Type Error";
return;
}
object emp = t.Assembly.CreateInstance("AppCode.Employe");
if (emp == null)
{
textBox1.Text = "Create Instance Error";
return;
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("Type:" + t.FullName);
sb.AppendLine("Context:");
sb.AppendLine(emp.ToString());
textBox1.Text = sb.ToString();
有参数构造函数
Type t = Type.GetType("AppCode.Employe");
if (t == null)
{
textBox1.Text = "Create Type Error";
return;
}
//构造函数参数列表如下
//public Employe(string userid, string username, int age)
//生成参数类型数组
Type ts = new Type { typeof(System.String),typeof(System.String), typeof(System.Int16) };
//获得构造函数
ConstructorInfo mi = t.GetConstructor(ts);
if (mi == null)
{
textBox1.Text = "Create ConstructorInfo Error";
return;
}
//生成参数值数组
object ps=new object;
ps[0] = "420106780911326";
ps = "wesker";
ps = 36;
object emp=mi.Invoke(ps);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Type:" + t.FullName);
sb.AppendLine("Context:");
sb.AppendLine(emp.ToString());
textBox1.Text = sb.ToString();
2.获得不同程序集内的类型的实例。
比如当前窗体程序要通过反射获得一个名为"compenent1"(文件名为compenent1.dll)的程序集中的类型的实例。
无参数构造函数
Type t = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\compenent1.dll").
GetType("compenent1.User");
if (t == null)
{
textBox1.Text = "Create Type Error";
return;
}
object user = t.Assembly.CreateInstance("compenent1.User");
if (user == null)
{
textBox1.Text = "Create Instance Error";
return;
}
StringBuilder sb = new StringBuilder();
sb.AppendLine("Type:" + t.FullName);
sb.AppendLine("Context:");
sb.AppendLine(user.ToString());
textBox1.Text = sb.ToString();
有参数的构造函数
Type t = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "\\compenent1.dll").
GetType("compenent1.User");
if (t == null)
{
textBox1.Text = "Create Type Error";
return;
}
//构造函数参数列表如下
//public Employe(string userid, string username, int age)
Type ts = new Type { typeof(System.String), typeof(System.String), typeof(System.Int16) };
ConstructorInfo mi = t.GetConstructor(ts);
if (mi == null)
{
textBox1.Text = "Create ConstructorInfo Error";
return;
}
object ps = new object;
ps[0] = "420106780911326";
ps = "wesker";
ps = 36;
object user = mi.Invoke(ps);
StringBuilder sb = new StringBuilder();
sb.AppendLine("Type:" + t.FullName);
sb.AppendLine("Context:");
sb.AppendLine(user.ToString());
textBox1.Text = sb.ToString();
3.使用反射调用方法
Type t = Type.GetType("AppCode.Employe");
if (t == null)
{
textBox1.Text = "Create Type Error";
return;
}
object emp = t.Assembly.CreateInstance("AppCode.Employe");
if (em