我有:
public class MyUserControl : WebUserControlBase <MyDocumentType>{...}
如果我在另一个班级中,如何获得MyDocumentType
的TypeName?
答案 0 :(得分:7)
您可以使用以下内容:
typeof(MyUserControl).BaseType.GetGenericArguments()[0]
答案 1 :(得分:3)
如果您知道该类直接从T
派生,则有很多答案显示如何获取WebUserControlBase<T>
的类型。如果您希望能够上层直到遇到WebUserControlBase<T>
:
var t = typeof(MyUserControl);
while (!t.IsGenericType
|| t.GetGenericTypeDefinition() != typeof(WebUserControlBase<>))
{
t = t.BaseType;
}
然后通过反映T
的泛型类型参数继续获取t
。
由于这是一个示例而非生产代码,因此我并未处理t
表示根本不是从WebUserControlBase<T>
派生的类型的情况。
答案 2 :(得分:1)
如果您使用的是.NET 4.5:
typeof(MyUserControl).BaseType.GenericTypeArguments.First();
答案 3 :(得分:1)
您可以使用Type.GetGenericArguments
方法。
返回表示类型参数的Type对象数组 泛型类型或泛型类型定义的类型参数。
像
typeof(MyUserControl).BaseType.GetGenericArguments()[0]
由于此方法的返回类型为System.Type[]
,因此数组元素将按照它们出现在泛型类型的类型参数列表中的顺序返回。