使用反射获取T的类型名称

时间:2013-03-20 09:39:22

标签: c# reflection

我有:

public class MyUserControl : WebUserControlBase <MyDocumentType>{...}

如果我在另一个班级中,如何获得MyDocumentType的TypeName?

4 个答案:

答案 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[],因此数组元素将按照它们出现在泛型类型的类型参数列表中的顺序返回。

相关问题