繁体   English   中英

结合使用Activator.CreateInstance()和属性

[英]Using Activator.CreateInstance() with properties

我在基本(抽象)类中具有以下属性:

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'

TheType是一个返回返回Type的属性,它本身不是Type

使用Activator.CreateInstance(Type)方法代替Activator.CreateInstance<T>()方法,即

var obj = Activator.CreateInstance(TheType);

由于您不知道将返回哪种Type TheType ,因此您将无法在运行时将其TheType转换为特定类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM