[英]Creating a generic based on class Type
如果我有通用類:
public class GenericTest<T> : IGenericTest {...}
我有一個Type的實例,我通過反射得到了,我怎么能用該Type實例化GenericType? 例如:
public IGenericTest CreateGenericTestFromType(Type tClass)
{
return (IGenericTest)(new GenericTest<tClass>());
}
當然,上面的方法不會編譯,但它說明了我正在嘗試做的事情。
您需要使用Type.MakeGenericType :
public IGenericTest CreateGenericTestFromType(Type tClass)
{
Type type = typeof(GenericTest<>).MakeGenericType(new Type[] { tClass });
return (IGenericTest) Activator.CreateInstance(type);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.