【问题标题】:Difference between .NET's System.Type.GenericTypeArguments and System.Type.GetGenericArguments().NET 的 System.Type.GenericTypeArguments 和 System.Type.GetGenericArguments() 之间的区别
【发布时间】:2015-08-04 12:25:13
【问题描述】:

为什么 .NET Framework 两者都提供

System.Type.GenericTypeArguments

System.Type.GetGenericArguments()

它们都返回给定泛型类型的类型参数(都作为Type[])?

似乎属性和方法公开了完全相同的功能,这意味着 API 的接口具有冗余/重复功能?

【问题讨论】:

    标签: .net generics system.type


    【解决方案1】:

    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

    【讨论】:

    • 真的吗?这很奇怪......如果 GenericTypeArguments 的目的就像你说的那样,那么它不应该是一个布尔值吗?!返回一个空数组有什么用——为了说明一个类型是否是泛型类型定义?!
    • @Veverke:如果类型是泛型类型的实现,它会返回一个类型数组。 typeof(List<>).GenericTypeArguments 返回一个空数组,typeof(List<int>).GenericTypeArguments 返回一个包含typeof(int) 的数组,typeof(List<>).GetGenericArguments() 返回一个包含泛型参数T 的类型的数组。
    • 哦...这更清楚了,尽管要跟上这些名字并不是一件容易的事...
    • 我忘记了 .NET 去年 11 月成为开源的......我想搜索代码,但认为它还没有发生。谢谢!
    【解决方案2】:

    当您查看这些成员的 MSDN 文章中的版本信息文档时,这一点会变得更加明显。 WinRT(又称 Windows 应用商店应用)支持 GenericTypeArguments 属性,但不支持 GetGenericArguments() 方法。

    WinRT 在 .NET Framework 4.5 版中引起了许多变化,但大多数变化并不那么明显。框架中内置的语言投影 涵盖了大多数基本类型系统差异,并隐藏了 WinRT 在其核心是基于 COM 的事实。但是,如果您使用反射,则必须以非常不同的方式处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 2012-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2011-10-02
      相关资源
      最近更新 更多