[英]Construct an instance of a concrete type of a generic, using reflection at runtime
考慮以下類別:
public class GenericClass<T>
{
public T Argument;
}
第二個類引用並使用GenericClass:
public class ClientClass
{
GenericClass<T> genclass = new GenericClass<T>();
}
我的問題是我在編譯時不知道T的類型。 我在運行時使用反射來獲取T的類型。在實例化GenericClass
是否可能以某種方式使用參數化表達式?
是的,但是您必須使用反射來構建您要查找的實際類型。
首先,您需要使用typeof
運算符來獲取開放的泛型:
var openType = typeof(GenericClass<>);
接下來,您需要構建所需的特定泛型。 假設您想要的類型T存儲在變量中,請type
:
var closedType = openType.MakeGenericType(type);
object instance = Activator.CreateInstance(closedType);
但是,正如xanatos在評論中指出的那樣,您應該意識到這會導致object
類型的成員。 為了能夠在沒有反射的情況下操縱對象,您有兩種選擇。
GenericClass
自GenericClass<T>
的父類GenericClass
,並在其上包含所有通用的方法。 (即GenericClass
包含不需要使用T
。 IInterface
,然后在T
上添加一個限制, where T : IInterface
。 然后,您可以將instance
為GenericClass<IInterface>
並以這種方式進行操作。 顯然,在這種情況下, type
必須實現IInterface
。 當然,您也可以僅保留object
引用並僅使用反射對其進行操作,或者使用dynamic
方法后期綁定任何方法調用-但是,這將在后台使用反射。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.