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

编程入门 行业动态 更新时间:2024-10-26 12:28:07
本文介绍了.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()等效项是什么?

本文发布于:2023-11-13 23:40:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585627.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   NETStandard   GetGenericArguments   Type   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!