繁体   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