我正要通过对反射和泛型的一些文章,我碰到下面的代码来:优势Activator.CreateInstance的
public static T CreateControlInstance<T>(FormControl parent)
where T : FormControl
{
T control = GetControlInstance<T>(parent);
//do something with control
}
public static T GetControlInstance<T>(FormControl parent)
{
return (T)Activator.CreateInstance(typeof(T), new object[] { parent });
}
这些方法中使用这样的:
MyButton b = CreateControlInstance<MyButton>(SomeformInstance);
许多控件是以这种方式创建的。我只想知道:
Q1。这种方法的优点是什么?
Q2。考虑到对象实例类型在编译时已知,这种方法的优点是什么? (我假设的按钮和FormControl
以某种方式与System.Windows.Forms.Control
)
编辑:
我发现这里类似的事情正在做 Create instance of generic type?
基本上我想创建(已知类型的)类型从运行时读取的字符串?
我想避免if-then-else根据字符串创建具体类型的对象的长列表..但没有线索。
任何人都有更好的解决方案,以避免反射以创建已知类型的元素。
末编辑
您可以添加对文章的引用吗? – 2011-02-03 11:47:12
这是一个人为的例子。也不是很好的一个,命名的选择是一个可怕的。 GetFooInstance不*建议创建* new * Foo。 – 2011-02-03 12:30:13