方法 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 的确切行为是什么?等效于 Type.GetGenericArguments的行为。 ()在.NET Standard 1.0中?
What is the exact behavior of GenericTypeArguments and what's the equivalent of Type.GetGenericArguments() in .NET Standard 1.0?
推荐答案进一步研究后, Type.GenericTypeArguments 似乎仅在类型不是泛型类型定义时返回任何内容。另一方面, TypeInfo.GenericTypeParameters 仅在类型为泛型类型定义时返回任何值。
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()等效项是什么?
发布评论