C#获得类型Generic< T>.给定T [英] C# get the the type Generic<T> given T
本文介绍了C#获得类型Generic< T>.给定T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在C#中有一个通用类,如下所示:
I have a generic class in C#, like this:
public class GenericClass<T> { ... }
现在,我有一个对象的 Type
对象,并且希望通过反射或其他方式获取 GenericClass< T>的
其中T对应于该Type对象,而我有我的对象. Type
对象;
Now, I have the Type
object for an object, and would like to, through reflection or otherwise, to get the Type
object for GenericClass<T>
where T corresponds to that Type object I have my object.
赞:
Type requiredT = myobject.GetType();
Type wantedType = typeof(GenericClass<requiredT>);
很明显,这种语法不起作用,但是我该怎么做呢?
Obviously this syntax doesn't work, but how do I do it?
推荐答案
是的,您可以:
Type requiredT = ...
Type genericType = typeof(GenericClass<>);
Type wantedType = genericType.MakeGenericType(requiredT);
这将为您提供 GenericClass< T>
类型对象,其中T对应于您的 requiredT
.
This will give you the GenericClass<T>
Type object, where T corresponds to your requiredT
.
然后您可以使用 Activator
构造一个实例,如下所示:
You can then construct an instance using Activator
, like this:
var instance = Activator.CreateInstance(wantedType, new Object[] { ...params });
这篇关于C#获得类型Generic< T>.给定T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文