2009-02-03 64 views
3

我真的很讨厌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's article甚至源代码System.Linq.Enumerablereflector但似乎缺少的东西。

这工作:

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

但这并不

extraDataLookup.GetValueOrDefault ("foo") 

,我应该怎么做。

PS。我只是在寻找解决通用类型推断问题的方法,而不是其他任何建议。谢谢。

回答

5

当你只需要两个时,你似乎正在用三种泛型定义扩展方法。 “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; 
}  
+0

woops。谢谢。现在像魔术一样工作 – 2009-02-03 04:39:37