【发布时间】:2015-08-04 12:25:13
【问题描述】:
为什么 .NET Framework 两者都提供
System.Type.GenericTypeArguments
和
System.Type.GetGenericArguments()
它们都返回给定泛型类型的类型参数(都作为Type[])?
似乎属性和方法公开了完全相同的功能,这意味着 API 的接口具有冗余/重复功能?
【问题讨论】:
标签: .net generics system.type
为什么 .NET Framework 两者都提供
System.Type.GenericTypeArguments
和
System.Type.GetGenericArguments()
它们都返回给定泛型类型的类型参数(都作为Type[])?
似乎属性和方法公开了完全相同的功能,这意味着 API 的接口具有冗余/重复功能?
【问题讨论】:
标签: .net generics system.type
GenericTypeArguments property 返回一个空数组,而GetGenericArguments method 返回一个包含泛型参数类型的数组。GenericTypeArguments 属性已添加到框架 4.5 中。GenericTypeArguments 属性实际上实现为在类型是泛型类型的实现时调用 GetGenericArguments:
public virtual Type[] GenericTypeArguments {
get {
if (IsGenericType && !IsGenericTypeDefinition){
return GetGenericArguments();
} else {
return Type.EmptyTypes;
}
}
}
来源:http://referencesource.microsoft.com/#mscorlib/system/type.cs,0aa31a7de47b9dc7
【讨论】:
typeof(List<>).GenericTypeArguments 返回一个空数组,typeof(List<int>).GenericTypeArguments 返回一个包含typeof(int) 的数组,typeof(List<>).GetGenericArguments() 返回一个包含泛型参数T 的类型的数组。
当您查看这些成员的 MSDN 文章中的版本信息文档时,这一点会变得更加明显。 WinRT(又称 Windows 应用商店应用)支持 GenericTypeArguments 属性,但不支持 GetGenericArguments() 方法。
WinRT 在 .NET Framework 4.5 版中引起了许多变化,但大多数变化并不那么明显。框架中内置的语言投影 涵盖了大多数基本类型系统差异,并隐藏了 WinRT 在其核心是基于 COM 的事实。但是,如果您使用反射,则必须以非常不同的方式处理它。
【讨论】: