.NETStandard 1.0 / .NET Core中的Type.GetGenericArguments()等效项是什么? [英] What is the equivalent of Type.GetGenericArguments() in .NETStandard 1.0 / .NET Core?

查看:106
本文介绍了.NETStandard 1.0 / .NET Core中的Type.GetGenericArguments()等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法 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()等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆