我在base(抽象)类中有以下属性:
protected abstract Type TheType { get; }
上述属性由子类实例化:
protected override Type TheType
{
get { return typeof (ChildClass); }
}
我希望在基类中实例化对象:
var obj = (TheType) Activator.CreateInstance<TheType>();
不幸的是,我收到以下编译错误:
Error 1 'BaseClass.TheType' is a 'property' but is used like a 'type'
在这种情况下,我如何调用Activator.CreateInstance()
?
PS:我已尝试将该属性更改为字段:
protected Type TheType;
我仍然遇到编译错误:
'BaseClass.TheType' is a 'field' but is used like a 'type'
答案 0 :(得分:4)
TheType
是一个返回Type
的属性,它本身不是Type
。
使用Activator.CreateInstance(Type)
方法代替Activator.CreateInstance<T>()
方法,即
var obj = Activator.CreateInstance(TheType);
因为您不知道将返回哪个Type
TheType
,所以您将无法在运行时将其强制转换为特定类型。