C#:将类类型保存到变量中?

Jos*_*nel 0 c#

我正在尝试将一些UserControl-Infos保存到List中,如下所示:

List<UserControlDetails> myList;
public UserControlDetails 
{
    string Description { get; set; }
    Type UserControlType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果我在ListView中显示此List,我希望能够启动我的UserControl,例如通过SelectedItem属性,如

 //SelectedItem.UserControlType = MyMainViewModel;
 var tmp = new SelectedItem.UserControlType(); //This will return a new instance of MainViewModel
Run Code Online (Sandbox Code Playgroud)

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

非常感谢!

干杯

编辑:感谢一堆回应.另一个问题:如何将"MaiNViewModel"的类型保存到类型变量中?我收到"类名无效"错误

EDIT2:知道了,它是typeof().我现在将尝试这些方法并尽快报告

Jon*_*eet 6

我想你想要:

object tmp = Activator.CreateInstance(SelectedItem.UserControlType);
Run Code Online (Sandbox Code Playgroud)

如果它总是会成为某种常见类型的后代(例如UserControl),那么你可以将其转换为:

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

这假设有一个公共无参数构造函数,因为这是Activator.CreateInstance调用.