Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 字典TryGetValue输出参数_C#_Dictionary - Fatal编程技术网

C# 字典TryGetValue输出参数

C# 字典TryGetValue输出参数,c#,dictionary,C#,Dictionary,TryGetValue是否更改输入参数 使用TryGetValue时,我倾向于: Dictionary<int, long> myDic; long lValue = -1; long lTemp1; if( myDic.TryGetValue(100, out lTemp1)){ lValue = lTemp1; } 像美国一样 当此方法返回时,如果找到指定键,则返回与该键关联的值;否则,将显示value参数类型的默认值 该值将被更改 如果你想缩短你的代码,你可以这样做

TryGetValue是否更改输入参数

使用TryGetValue时,我倾向于:

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

if( myDic.TryGetValue(100, out lTemp1)){
    lValue = lTemp1;
}
像美国一样

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

该值将被更改

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

Dictionary<int, long> myDic;

if( !myDic.TryGetValue(100, out var lValue))
{
    lValue = -1;
}

现场工作示例位于

。。。或者,当此方法返回与指定键关联的值(如果找到该键)时,读取文档通常非常有用;否则,值参数类型的默认值。通过创建单独的临时变量所做的唯一一件事就是占用内存空间。为什么不
if(myDic.TryGetValue(nKeyToLookup,out long lValue)
您实际上可以做
if(myDic.TryGetValue(100,out var lValue){}
左值将被声明并正确初始化(要么到
默认值(长)
,即
0L
,要么到正确的值(如果找到),“TryGetValue是否更改输入参数?”--我一点也不理解你的问题。如果它不改变输入参数的值,那么
lTemp1
怎么会有你想要分配给
lValue
的值呢?这个问题毫无意义。我明白了。这意味着我必须做些事情来保持初始值。因为额外的代码是不可避免的,我希望它保持不变已更改,否则似乎有必要引入另一个变量。我认为这可能是合理的解决方案。因为如果有可能无法查找任何项,为什么必须指定值。@Chengting因为在C#中,必须为out参数指定值,否则代码将无法编译。所以我认为可能最初的TryGetValue最好使用ref而不是out。因为使用“Try”函数可能会失败,所以我自己会准备另一个更有意义的默认值,而不是类型的默认值。如果TryGetValue找不到任何内容,它就不必费事进行赋值。
Dictionary<int, long> myDic;

if( !myDic.TryGetValue(100, out var lValue))
{
    lValue = -1;
}
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;
    }
}