.NETStandard 1.0/.NET Core 中 Type.GetGenericArguments() 的等价物是什么? [英] What is the equivalent of Type.GetGenericArguments() in .NETStandard 1.0 / .NET Core?
问题描述
方法 System.Type.GetGenericArguments()
在 .NETStandard 1.0 中缺失",我认为 TypeInfo.GenericTypeArguments
是 的替代品GetGenericArguments()
,但不幸的是,当提供一个开放的泛型类型时,它们的行为会有所不同.以下面的代码为例:
The method System.Type.GetGenericArguments()
is 'missing' from .NETStandard 1.0, and I thought that the TypeInfo.GenericTypeArguments
was the replacement for GetGenericArguments()
, but unfortuntely they behave differently when supplied with an open generic type. Take for instance the following code:
Type type = typeof(ICommandHandler<>);
type.GetGenericArguments(); // return { TCommand }
type.GetTypeInfo().GenericTypeArguments; // returns empty array
虽然 GetGenericArguments()
方法返回泛型类型参数 TCommand
,GenericTypeArguments
只是返回一个空数组,用于相同的开放泛型类型.
While the GetGenericArguments()
method returns the generic type argument TCommand
, the GenericTypeArguments
simply returns an empty array for the same open-generic type.
GenericTypeArguments
的确切行为是什么? .NET Standard 1.0 中 Type.GetGenericArguments()
的等价物是什么?
What is the exact behavior of GenericTypeArguments
and what's the equivalent of Type.GetGenericArguments()
in .NET Standard 1.0?
推荐答案
经过进一步调查,Type.GenericTypeArguments
似乎只在类型不是泛型类型定义时返回任何内容.另一方面,TypeInfo.GenericTypeParameters
仅在类型是泛型类型定义时返回 any.
After further investigation, the Type.GenericTypeArguments
seems to only return anything if the type isn't a generic type definition. The TypeInfo.GenericTypeParameters
on the other hand, only returns any if the type is a generic type definition.
以下代码模仿了 Type.GetGenericArguments()
的行为:
The following code mimics the behavior of Type.GetGenericArguments()
:
type.GetTypeInfo().IsGenericTypeDefinition
? type.GetTypeInfo().GenericTypeParameters
: type.GetTypeInfo().GenericTypeArguments;
这篇关于.NETStandard 1.0/.NET Core 中 Type.GetGenericArguments() 的等价物是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!