目前我正在使用

var x = dict.ContainsKey(key) ? dict[key] : defaultValue

我想要一些方法让字典[key]为非耐用键返回null,所以我可以写一些像

var x =  dict[key] ?? defaultValue;

这也是linq查询等的一部分,所以我更喜欢单行解决方案。

有帮助吗?

解决方案

使用扩展方法:

public static class MyHelper
{
    public static V GetValueOrDefault<K, V>(this IDictionary<K, V> dic, 
                                            K key, 
                                            V defaultVal = default(V))
    {
        V ret;
        bool found = dic.TryGetValue(key, out ret);
        if (found) { return ret; }
        return defaultVal;
    }
    void Example()
    {
        var dict = new Dictionary<int, string>();
        dict.GetValueOrDefault(42, "default");
    }
}

其他提示

您可以使用辅助方法:

public abstract class MyHelper {
    public static V GetValueOrDefault<K,V>( Dictionary<K,V> dic, K key ) {
        V ret;
        bool found = dic.TryGetValue( key, out ret );
        if ( found ) { return ret; }
        return default(V);
    }
}

var x = MyHelper.GetValueOrDefault( dic, key );

这是“终极”解决方案,它实现为扩展方法,使用IDictionary接口,提供可选的默认值,并简明扼要地写。

public static TV GetValueOrDefault<TK, TV>(this IDictionary<TK, TV> dic, TK key,
    TV defaultVal=default(TV))
{
    TV val;
    return dic.TryGetValue(key, out val) 
        ? val 
        : defaultVal;
}

不是简单的 TryGetValue(key,out value)你在寻找什么?引用MSDN:

When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.

来自 http://msdn.microsoft。 COM / EN-US /库/ bb347013(v = VS.90)的.aspx

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top