簡體   English   中英

.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.GenericTypeArgumentsGetGenericArguments()的替代品,但是當提供開放泛型類型時,它們的行為很不幸。 以下面的代碼為例:

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

雖然GetGenericArguments()方法返回泛型類型參數TCommand ,但GenericTypeArguments只返回相同open-generic類型的空數組。

GenericTypeArguments的確切行為是什么?在.NET Standard 1.0中, Type.GetGenericArguments()的等價物是什么?

經過進一步調查后,如果類型不是泛型類型定義,則Type.GenericTypeArguments似乎只返回任何內容。 另一方面, TypeInfo.GenericTypeParameters僅在類型是泛型類型定義時才返回any。

以下代碼模仿Type.GetGenericArguments()的行為:

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

畢竟,這可能會成為評論(而不是答案)。

在.NET 4.6.1上, System.Type上有兩個成員,即:

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

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

System.Reflection.TypeInfo上加一個成員,即:

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

共有三名成員。

但是,最先提到的兩個成員也是System.Reflection.TypeInfo 繼承的System.Reflection.TypeInfoSystem.Type的子類。

在.NET 4.6.1上,當你type.GetTypeInfo().GenericTypeArguments (如你的問題中)時,你真的在Type上調用屬性,即我的成員標記為/* 2 */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM