简体   繁体   English

编写通用扩展方法时类型推断有问题

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

I really hate sometimes how IDictionary<TKey, TValue> [key] will throw an exception if the key doesn't exist in the dictionary. 我真的很讨厌如果字典中不存在IDictionary<TKey, TValue> [key]将如何抛出异常。

Of course there is TryGetValue() , but that seems to have been optimized for performance and not usability. 当然有TryGetValue() ,但似乎已针对性能而非可用性进行了优化。

So I thought, oh I'll just make an extension method for it - which I did : 所以我想,哦,我只是为它做一个扩展方法 - 我做了:

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);
        }
    }    
}

This works fine EXCEPT I cannot seem to get type inference working. 这工作正常除了我似乎无法得到类型推断工作。

Obviously I want to be able to do the following : 显然我希望能够做到以下几点:

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

and then be able to access the value : 然后能够访问该值:

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

I've looked at a few things about type inference, inlucing Jon Skeet's article and even sourcecode to System.Linq.Enumerable in reflector but seem to be missing something. 我已经看了一些关于类型推断的事情,将Jon Skeet的文章甚至源代码都反映到了反射器中的 System.Linq.Enumerable ,但似乎缺少了一些东西。

This works : 这有效:

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

but this doesn't 但事实并非如此

extraDataLookup.GetValueOrDefault ("foo") 

What should I be doing. 我该怎么办

PS. PS。 I'm only looking for solutions to the generic type inference problem, not any other suggestions. 我只是在寻找泛型类型推理问题的解决方案,而不是任何其他建议。 Thanks. 谢谢。

You seem to be defining your extension method with three generic types when you only need two. 当您只需要两个泛型类型时,您似乎正在使用三种泛型类型定义扩展方法。 "TValue" and "TType" mean the same thing, don't they? “TValue”和“TType”意思相同,不是吗? Try this: 试试这个:

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