2009-10-27 156 views
0

我想一些用户控件,相关信息保存到像这样的列表:C#:将类类型保存到变量中?

List<UserControlDetails> myList; 
public UserControlDetails 
{ 
    string Description { get; set; } 
    Type UserControlType { get; set; } 
} 

现在,如果我在一个ListView显示此列表,我希望能够例如开始我的用户通过SelectedItem属性如

//SelectedItem.UserControlType = MyMainViewModel; 
var tmp = new SelectedItem.UserControlType(); //This will return a new instance of MainViewModel 

任何想法如何做到这一点?还是其他想法?

非常感谢!

干杯

编辑:感谢一堆的答复。另一个问题:如何将“MaiNViewModel”的类型保存到类型变量中?我得到“类名称无效”错误

编辑2:明白了,它是typeof()。现在我会尝试的方法和尽快

回答

6

报到我想你想:

object tmp = Activator.CreateInstance(SelectedItem.UserControlType); 

如果总是会出现一些常见类型的后裔(如UserControl),那么你可以丢:

Type type = SelectedItem.UserControlType; 
UserControl tmp = (UserControl) Activator.CreateInstance(type); 
// You can now use the members of UserControl on tmp. 

这是假设有一个公共的无参数的构造函数,虽然,因为这就是Activator.CreateInstance电话。

0
var tmp = Activator.CreateInstance(SelectedItem.UserControlType); 
0
// assuming you want to use the default constructor 
object control = Activator.CreateInstance(SelectedItem.UserControlType); 
4

脏和简单的方法:Activator.CreateInstance。 恕我直言,你应该尝试一下factory

+0

提及工厂+1。如果仅用于创建实例,则不应公开该类型。 – SoftMemes 2009-10-27 15:12:14

+0

感谢您指出工厂模式! – 2009-10-27 15:36:56

0

您可以使用Activator.CreateInstance(类型t)从类型信息创建新实例。