【发布时间】:2013-03-20 09:39:22
【问题描述】:
我有:
public class MyUserControl : WebUserControlBase <MyDocumentType>{...}
如果我在另一个班级,如何获得 MyDocumentType 的 TypeName?
【问题讨论】:
标签: c# reflection
我有:
public class MyUserControl : WebUserControlBase <MyDocumentType>{...}
如果我在另一个班级,如何获得 MyDocumentType 的 TypeName?
【问题讨论】:
标签: c# reflection
你可以这样使用:
typeof(MyUserControl).BaseType.GetGenericArguments()[0]
【讨论】:
如果您知道该类直接派生自WebUserControlBase<T>,那么有很多答案显示如何获取T 的类型。如果您希望能够提升层次结构直到遇到WebUserControlBase<T>,以下是如何做到这一点:
var t = typeof(MyUserControl);
while (!t.IsGenericType
|| t.GetGenericTypeDefinition() != typeof(WebUserControlBase<>))
{
t = t.BaseType;
}
然后通过反射t 的泛型类型参数继续得到T。
由于这是一个示例而不是生产代码,我不会处理 t 表示的类型根本不是从 WebUserControlBase<T> 派生的情况。
【讨论】:
你可以使用Type.GetGenericArguments方法。
返回一个 Type 对象数组,这些对象表示 泛型类型或泛型类型定义的类型参数。
喜欢
typeof(MyUserControl).BaseType.GetGenericArguments()[0]
由于此方法的返回类型为System.Type[],因此数组元素按照它们在泛型类型参数列表中出现的顺序返回。
【讨论】:
如果您使用的是 .NET 4.5:
typeof(MyUserControl).BaseType.GenericTypeArguments.First();
【讨论】:
GenericTypeArguments 属性只存在于 .NET 4.5 开始。