C#:将类类型保存到变量中?
我正在尝试将一些UserControl信息保存到如下列表中:C#:将类类型保存到变量中?,c#,C#,我正在尝试将一些UserControl信息保存到如下列表中: List<UserControlDetails> myList; public UserControlDetails { string Description { get; set; } Type UserControlType { get; set; } } 有什么办法吗?还是其他想法 非常感谢 干杯 编辑:非常感谢您的回复。另一个问题:如何将“MaiNViewModel”的类型保存到类型变量中?我得
List<UserControlDetails> myList;
public UserControlDetails
{
string Description { get; set; }
Type UserControlType { get; set; }
}
有什么办法吗?还是其他想法
非常感谢
干杯
编辑:非常感谢您的回复。另一个问题:如何将“MaiNViewModel”的类型保存到类型变量中?我得到一个“类名无效”错误
编辑2:明白了,是typeof()。我现在将尝试这些方法,并尽快向您报告我想您需要:
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(类型t)从类型信息创建新实例。+1表示工厂。如果仅用于创建实例,则不应公开该类型。
Type type = SelectedItem.UserControlType;
UserControl tmp = (UserControl) Activator.CreateInstance(type);
// You can now use the members of UserControl on tmp.
var tmp = Activator.CreateInstance(SelectedItem.UserControlType);
// assuming you want to use the default constructor
object control = Activator.CreateInstance(SelectedItem.UserControlType);