簡體   English   中英

如何使用類型參數從通用類型中提取原始通用類型

[英]How to extract the raw generic type out of generic type with type parameters

假設我有一個運行時對象的通用類型和同一類的原始通用類型,例如

var type = (new List<Int32>()).GetType();
var genericListType = typeof(List<>);

我需要一種GetRawGenericType方法,因此表達式

GetRawGenericType(type) == genericListType

返回true。 有辦法實現嗎?

備注:

我不知道對象的類型,它可以是任何通用類型。 在我編寫的代碼中,我必須知道確切的泛型類型,因為它將用作字典中的鍵,例如:

private readonly Dictionary<Type, TValue> Mapping = 
    new Dictionary<Type, TValue> { 
            {typeof(IEnumerable<>), *SomeValue*},
            ...
        }

預先感謝您的寶貴時間。

您正在尋找Type.GetGenericTypeDefinition

使用GetGenericTypeDefinition方法

var type = (new List<Int32>()).GetType();
var genericListType = typeof(List<>);

Console.WriteLine(type.GetGenericTypeDefinition() == genericListType);

節目

true

暫無
暫無

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

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