简体   繁体   English

.NETStandard 1.0 / .NET Core中Type.GetGenericArguments()的等价物是什么?

[英]What is the equivalent of Type.GetGenericArguments() in .NETStandard 1.0 / .NET Core?

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. 方法System.Type.GetGenericArguments()从.NETStandard 1.0中“丢失”,我认为TypeInfo.GenericTypeArgumentsGetGenericArguments()的替代品,但是当提供开放泛型类型时,它们的行为很不幸。 Take for instance the following code: 以下面的代码为例:

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

While the GetGenericArguments() method returns the generic type argument TCommand , the GenericTypeArguments simply returns an empty array for the same open-generic type. 虽然GetGenericArguments()方法返回泛型类型参数TCommand ,但GenericTypeArguments只返回相同open-generic类型的空数组。

What is the exact behavior of GenericTypeArguments and what's the equivalent of Type.GetGenericArguments() in .NET Standard 1.0? GenericTypeArguments的确切行为是什么?在.NET Standard 1.0中, Type.GetGenericArguments()的等价物是什么?

After further investigation, the Type.GenericTypeArguments seems to only return anything if the type isn't a generic type definition. 经过进一步调查后,如果类型不是泛型类型定义,则Type.GenericTypeArguments似乎只返回任何内容。 The TypeInfo.GenericTypeParameters on the other hand, only returns any if the type is a generic type definition. 另一方面, TypeInfo.GenericTypeParameters仅在类型是泛型类型定义时才返回any。

The following code mimics the behavior of Type.GetGenericArguments() : 以下代码模仿Type.GetGenericArguments()的行为:

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

This may turn out to be a comment (not an answer) after all. 毕竟,这可能会成为评论(而不是答案)。

On .NET 4.6.1, there are two members on System.Type , namely: 在.NET 4.6.1上, System.Type上有两个成员,即:

/* 1 */ type.GetGenericArguments()               // returns { TCommand, }

/* 2 */ type.GenericTypeArguments                // returns empty array

plus one member on System.Reflection.TypeInfo , namely: System.Reflection.TypeInfo上加一个成员,即:

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

for a total of three members. 共有三名成员。

However, the two first-mentioned members are also inherited by System.Reflection.TypeInfo , a subclass of System.Type . 但是,最先提到的两个成员也是System.Reflection.TypeInfo 继承的System.Reflection.TypeInfoSystem.Type的子类。

On .NET 4.6.1, when you do type.GetTypeInfo().GenericTypeArguments (as in your question), you really call the property on Type , ie my member marked /* 2 */ . 在.NET 4.6.1上,当你type.GetTypeInfo().GenericTypeArguments (如你的问题中)时,你真的在Type上调用属性,即我的成员标记为/* 2 */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM