字典 TryGetValue 输出参数

Che*_*ing 4 c# dictionary

TryGetValue 是否更改输入参数?

当使用 TryGetValue 时,我倾向于这样做:

Dictionary<int, long> myDic;
long lValue = -1;
long lTemp1;

if( myDic.TryGetValue(100, out lTemp1)){
    lValue = lTemp1;
}
Run Code Online (Sandbox Code Playgroud)

我应该直接这样写吗?

myDic.TryGetValue(nKeyToLookup, out lValue);
Run Code Online (Sandbox Code Playgroud)

Sir*_*ufo 5

正如文档所述

当此方法返回时,如果找到该键,则返回与指定键关联的值;否则,为 value 参数类型的默认值。

该值将会改变。

如果你想缩短你的代码,你可以这样做

Dictionary<int, long> myDic;

if( !myDic.TryGetValue(100, out var lValue))
{
    lValue = -1;
}
Run Code Online (Sandbox Code Playgroud)

更新

您可以编写一个自定义TryGetValue扩展方法,它接受ref TValue value

public static class DictionaryExtensions
{
    public static bool TryGetValue<TKey,TValue>( this IDictionary<TKey,TValue> dict, TKey key, ref TValue value )
    {
        var result = dict.TryGetValue( key, out var foundValue );
        if ( result )
            value = foundValue;
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

.net fiddle的实时工作示例