簡體   English   中英

比較通用接口類型

[英]Comparing generic interface types

我需要檢測IDictionary<string, string>類型的對象是否為IDictionary<,>並且在提出正確的比較邏輯時遇到了麻煩。

我嘗試了以下方法:

typeof(IDictionary<string, string>)
       .GetInterface(typeof(IDictionary<,>).Name);

typeof(IDictionary<string, string>)
       .GetGenericTypeDefinition()
       .GetInterface(typeof(IDictionary<,>).Name);

調用typeof(Dictionary<string,string>).GetInterface(comparisonType.Name)返回預期的非null結果,但是如果我比較IDictionary<string,string>類型,則GetInterface()返回null。 同樣,在GenericTypeDefinition上進行比較也將返回null。

typeof(IDictionary<string, string>).GetGenericTypeDefinition() == typeof(IDictionary<,>)
static void Main(string[] args)
    {
        var x = typeof(IDictionary<string, string>);
        var y = typeof(IDictionary<,>);

        Console.WriteLine(x.GetGenericTypeDefinition() == y);
    }

返回true

暫無
暫無

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

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