c# - 编写泛型扩展方法时的类型推断问题

标签 c# generics extension-methods

有时候我真的很讨厌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.Enumerable 的源代码在 reflector但似乎缺少了一些东西。

这个有效:

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

但这不是

extraDataLookup.GetValueOrDefault ("foo") 

我应该做什么。

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

最佳答案

当您只需要两个泛型时,您似乎在定义扩展方法。 “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;
}    

关于c# - 编写泛型扩展方法时的类型推断问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/506003/

相关文章:

c# - 扩展方法试图调用 protected 方法/动态参数的错误展示

c# - C#动态指定类型

c# - Ajax 不进行函数调用

c# - StackOverflowException 对嵌套数据使用 Linq(Kit)

c# - 如何从代码隐藏中调用此脚本?

typescript - 泛型函数的返回类型

java - 尝试了解 Java 泛型

java - 在泛型类的静态类中使用泛型类型

c# - 扩展方法优先级

c# - 是否可以只为 List<T> 编写扩展方法,其中 T 是从类 K 继承的类