[英]Using Activator.CreateInstance() with properties
I have the following property in a base (abstract) class: 我在基本(抽象)类中具有以下属性:
protected abstract Type TheType { get; }
The above property is instantiated by child classes: 上面的属性由子类实例化:
protected override Type TheType
{
get { return typeof (ChildClass); }
}
I'd like to instantiate the object in the base class: 我想实例化基类中的对象:
var obj = (TheType) Activator.CreateInstance<TheType>();
Unfortunately, I get the following compilation error: 不幸的是,我收到以下编译错误:
Error 1 'BaseClass.TheType' is a 'property' but is used like a 'type'
How may I invoke Activator.CreateInstance()
in this scenario? 在这种情况下如何调用
Activator.CreateInstance()
?
PS: I've tried changing the property to a field: PS:我尝试将属性更改为字段:
protected Type TheType;
Still I get compilation error: 仍然出现编译错误:
'BaseClass.TheType' is a 'field' but is used like a 'type'
TheType
is a property which returns returns a Type
, it is not a Type
itself. TheType
是一个返回返回Type
的属性,它本身不是Type
。
Use the Activator.CreateInstance(Type)
method instead of the Activator.CreateInstance<T>()
method, ie 使用
Activator.CreateInstance(Type)
方法代替Activator.CreateInstance<T>()
方法,即
var obj = Activator.CreateInstance(TheType);
Because you do not know which Type
TheType
will return, you will be unable to cast it to a specific type at runtime. 由于您不知道将返回哪种
Type
TheType
,因此您将无法在运行时将其TheType
转换为特定类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.