簡體   English   中英

編寫通用擴展方法時類型推斷有問題

[英]Trouble with type inference in writing generic extension method

我真的很討厭如果字典中不存在IDictionary<TKey, TValue> [key]將如何拋出異常。

當然有TryGetValue() ,但似乎已針對性能而非可用性進行了優化。

所以我想,哦,我只是為它做一個擴展方法 - 我做了:

public static class CollectionExtensions
{
    public static TType GetValueOrDefault<TKeyType, TValue, TType>(this IDictionary<TKeyType, TType> dictionary, TKeyType key)
    {
        TType value = default(TType);

        // attempt to get the value of the key from the dictionary
        // if the key doesn't exist just return null
        if (dictionary.TryGetValue(key, out value))
        {
            return value;
        }
        else
        {
            return default(TType);
        }
    }    
}

這工作正常除了我似乎無法得到類型推斷工作。

顯然我希望能夠做到以下幾點:

var extraDataLookup = new Dictionary<string, string>();
extraDataLookup["zipcode"] = model.Zipcode; 

然后能夠訪問該值:

var zipcode = extraDataLookup.GetValueOrDefault("zipcode");
var foo = extraDataLookup.GetValueOrDefault("foo"); // should be null

我已經看了一些關於類型推斷的事情,將Jon Skeet的文章甚至源代碼都反映到了反射器中的 System.Linq.Enumerable ,但似乎缺少了一些東西。

這有效:

extraDataLookup.GetValueOrDefault<string, string,string> ("foo") 

但事實並非如此

extraDataLookup.GetValueOrDefault ("foo") 

我該怎么辦

PS。 我只是在尋找泛型類型推理問題的解決方案,而不是任何其他建議。 謝謝。

當您只需要兩個泛型類型時,您似乎正在使用三種泛型類型定義擴展方法。 “TValue”和“TType”意思相同,不是嗎? 試試這個:

public static TValue GetValueOrDefault<TKey, TValue>(
    this IDictionary<TKey, TValue> dictionary, TKey key)
{
    TValue value;
    // attempt to get the value of the key from the dictionary
    dictionary.TryGetValue(key, out value);
    return value;
}    

暫無
暫無

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

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