【问题标题】:What is the equivalent of Type.GetGenericArguments() in .NETStandard 1.0 / .NET Core?.NETStandard 1.0 / .NET Core 中的 Type.GetGenericArguments() 等价物是什么?
【发布时间】:2016-12-31 22:57:27
【问题描述】:

System.Type.GetGenericArguments() 方法在 .NETStandard 1.0 中“缺失”,我认为 TypeInfo.GenericTypeArgumentsGetGenericArguments() 的替代品,但不幸的是,它们在提供开放的泛型类型时表现不同。以下面的代码为例:

Type type = typeof(ICommandHandler<>);
type.GetGenericArguments(); // return { TCommand }
type.GetTypeInfo().GenericTypeArguments; // returns empty array

虽然GetGenericArguments() 方法返回泛型类型参数TCommand,但GenericTypeArguments 只为相同的开放泛型类型返回一个空数组。

GenericTypeArguments 的确切行为是什么?在 .NET Standard 1.0 中 Type.GetGenericArguments() 的等价物是什么?

【问题讨论】:

  • @DavidL:.NETStandard 是 he .NET Standard Library is a formal specification of .NET APIs that are intended to be available on all .NET runtimes。 .NET 1.0 太旧了,而 .NETStandard 是新的;新的 PCL 更准确。
  • 注意一个是标准,一个是标准的实现。来自文章:“.NET Core 1.0 实现了 .NET Standard Library 1.6”
  • 此外,根据该图表,.NET Standard 1.0 的唯一实现是 Windows Phone Silverlight 8.0。
  • 你有.GetTypeInfo().GenericTypeParameters吗?
  • 由于您将类型指定为ICommandHandler&lt;&gt;,因此没有泛型类型参数。如果你给了它ICommandHandler&lt;string&gt;,你就会在那个数组中有一个项目。

标签: c# .net .net-core .net-standard


【解决方案1】:

经过进一步调查,Type.GenericTypeArguments 似乎只在类型不是泛型类型定义时才返回任何内容。另一方面,TypeInfo.GenericTypeParameters 仅在类型是泛型类型定义时才返回任何类型。

以下代码模仿Type.GetGenericArguments()的行为:

type.GetTypeInfo().IsGenericTypeDefinition 
    ? type.GetTypeInfo().GenericTypeParameters 
    : type.GetTypeInfo().GenericTypeArguments;

【讨论】:

    【解决方案2】:

    毕竟这可能是一个评论(而不是一个答案)。

    .NET 4.6.1 上,System.Type 上有两个成员,分别是:

    /* 1 */ type.GetGenericArguments()               // returns { TCommand, }
    
    /* 2 */ type.GenericTypeArguments                // returns empty array
    

    System.Reflection.TypeInfo上加一个成员,即:

    /* 3 */ type.GetTypeInfo().GenericTypeParameters // returns { TCommand, }
    

    总共三个成员。

    不过,前面提到的两个成员也继承System.Reflection.TypeInfoSystem.Type 的子类。

    在 .NET 4.6.1 上,当您执行 type.GetTypeInfo().GenericTypeArguments(如您的问题)时,您确实调用了 Type 上的属性,即我的成员标记为 /* 2 */

    【讨论】:

    • 这是一个有趣的观察。不幸的是,它没有回答我的问题。知道如何在 .NET Standard 1.0 下获取开放的泛型类型参数吗?
    • @Steven 不,很遗憾不是。如果我正确理解 Scott Chamberlain 对您的问题的评论,这可能会激发某人为 .NET Standard 1.5(edit: 甚至可能是 .NET Standard 1.1)或更高版本的解决方案。拥有三个名字GetGenericArguments()GenericTypeArgumentsGenericTypeParameters 是多么令人困惑。从某种意义上说,Microsoft .NET Framework 已经变得一团糟。 “.NET Standard”(也)的目的是整理这样的事情吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多