![](/img/trans.png)
[英]Using FastActivator in place of 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.