C#如何获取给定T的泛型类型Generic<T>

3

我有一个C#中的通用类,就像这样:

   public class GenericClass<T> { ... }

现在,我有一个对象的 Type 对象,并希望通过反射或其他方式获取 GenericClass<T>Type 对象,其中 T 对应于我拥有的对象的 Type 对象。

就像这样:

   Type requiredT = myobject.GetType();
   Type wantedType = typeof(GenericClass<requiredT>);

显然,这种语法无效,但我该如何实现?
3个回答

9

可以的:

Type requiredT = ...
Type genericType = typeof(GenericClass<>);
Type wantedType = genericType.MakeGenericType(requiredT);

这将为您提供GenericClass<T>类型的对象,其中T对应于您的requiredT
然后,您可以使用Activator构造一个实例,像这样:
var instance = Activator.CreateInstance(wantedType, new Object[] { ...params });

5
Type requiredT = myobject.GetType();
Type genericType = typeof(GenericClass<>);
Type wantedType = genericType.MakeGenericType(requiredT);

5
Type wantedType = typeof(GenericClass<>).MakeGenericType(requiredT);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接