呈顼I渝

C# 使用反射实现根据名称动态创建窗体的几种方法

//方法1使用activator方法创建实例


{
	string str = null;

	str = "Form2";
	//必须是 命名空间+点+窗体类名(这里假设为命名空间为空)

	Assembly tempAssembly = Assembly.GetExecutingAssembly();

	Type t = tempAssembly.GetType(str);

	object[] args = null;

	object o = System.Activator.CreateInstance(t, args);

	((Form2)o).Show();

	//Dim frm2 As Form = CType(tempAssembly.CreateInstance(str), Form)

	//frm2.Show()

	//////////////////方法2使用构造函数的invoke方法创建实例。

	Type[] ty = { };
	//该构造函数没有参数

	ConstructorInfo c = t.GetConstructor(ty);
	//获得没有参数的构造函数

	object[] args1 = null;
	//参数为空

	object p = c.Invoke(null);
	//创建实例时参数为空

	((Form2)p).Show();

	//方法3 ‘///////////////////////////////////////使用assembly.createinstance方法创建实例

	string str = null;

	str = "Form2";
	//必须是 命名空间+点+窗体类名
	System.Reflection.Assembly tempAssembly = System.Reflection.Assembly.GetExecutingAssembly();
	Form frm2 = (Form)tempAssembly.CreateInstance(str);
	frm2.Show();
}

posted on 2011-07-14 15:55  呈顼  阅读(2917)  评论(1编辑  收藏  举报

导航