I have:
public class MyUserControl : WebUserControlBase <MyDocumentType>{...}
How do I get the TypeName of MyDocumentType if I'm in another class?
I have:
public class MyUserControl : WebUserControlBase <MyDocumentType>{...}
How do I get the TypeName of MyDocumentType if I'm in another class?
你可以使用这样的东西:
typeof(MyUserControl).BaseType.GetGenericArguments()[0]
There are plenty answers showing how to get the type of T if you know that the class derives directly from WebUserControlBase<T>. Here's how to do it if you want to be able to go up the hierarchy until you encounter the WebUserControlBase<T>:
var t = typeof(MyUserControl);
while (!t.IsGenericType
|| t.GetGenericTypeDefinition() != typeof(WebUserControlBase<>))
{
t = t.BaseType;
}
And then go on to get T by reflecting on the generic type arguments of t.
Since this is an example and not production code, I 'm not handling the case where t represents a type that does not derive from WebUserControlBase<T> at all.
如果您使用的是 .NET 4.5:
typeof(MyUserControl).BaseType.GenericTypeArguments.First();
你可以使用Type.GetGenericArguments方法。
返回表示泛型类型的类型参数或泛型类型定义的类型参数的 Type 对象数组。
喜欢
typeof(MyUserControl).BaseType.GetGenericArguments()[0]
由于此方法的返回类型是 System.Type[],因此数组元素按照它们在泛型类型的类型参数列表中出现的顺序返回。