C# get the the type Generic<T> given T

橙三吉。 提交于 2021-02-07 22:16:08

问题


I have a generic class in C#, like this:

   public class GenericClass<T> { ... }

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.

Like this:

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

Obviously this syntax doesn't work, but how do I do it?


回答1:


Yes, you can:

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

This will give you the GenericClass<T> Type object, where T corresponds to your requiredT.

You can then construct an instance using Activator, like this:

var instance = Activator.CreateInstance(wantedType, new Object[] { ...params });



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/1537466/c-sharp-get-the-the-type-generict-given-t

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!