如何用c#如何动态创建类
类 Assembly, Activator 调用的方法名都是CreateInstance 。
不知道这两个类有没有联系,先看下面一些事例 ,后面2个没有测试。应该可以的。根据自己情况具体要自己修改。
petshop 中的一个写法
string className = path + ".Item";
return (PetShop.IDAL.IItem)Assembly.Load(path).CreateInstance(className);
另一个。。。。
// 程序集名称
string assemblyName = "abc.Business";
// 类名称
string className = "SampleBusiness";
// 获得指定名称的类型:程序集名称 + 类名称
Type type = Type.GetType(assemblyName + "." + className);
// 创建类型的一个实例
object obj = Activator.CreateInstance(type);
// 将实例强制转换成指定的类型
BaseBusiness curBusiness = (BaseBusiness)obj;
在来一种
private void btnShow_Click(object sender, System.EventArgs e)
{
Type type = Type.GetType("ReflectionTest.Form2");
System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(type);
//根据名称创建对象实例
Object obj = a.CreateInstance("ReflectionTest.Form2");
//调用对象方法或属性等
type.InvokeMember("Show",System.Reflection.BindingFlags.InvokeMethod,null,obj,null);
}