2017-10-12 68 views
0
 Dictionary<string, int> test = new Dictionary<string, int>(); 
     test.Add("dave", 12); 
     test.Add("john", 14); 

     int v; 

     test.TryGetValue("dave", out int v) 
     { 

      Console.WriteLine(v); 

     } 

这个简单的C#代码给出了“最佳重载方法匹配有一些无效参数”错误。你能告诉我错误的来源吗?谢谢。C#字典,这个简单代码中TryGetValue错误的来源是什么

+0

您正在使用哪种版本的编译器?一旦我修复了语法错误,VS2017就喜欢那个代码。请发布完整,有效的示例代码,以便在某些特定的命名版本的编译器中可靠地重现问题。 –

+3

'out int value'只有C#7 – haim770

+3

你是否错过'test.TryGetValue'附近的if语句? –

回答

2

OP是VS2012,不使用C#7。

首先,在参数列表中去掉int。它不可能存在于您的C#版本中。

其次,把一个分号TryGetValue()调用后...

int v; 
test.TryGetValue("dave", out v); 
Console.WriteLine(v); 

或者换一个如果:

int v; 
if (test.TryGetValue("dave", out v)) 
{ 
    Console.WriteLine(v); 
} 
0

“value”是您已经声明的变量,还是您离开TryGetValue的intellisense示例?很确定这是后一种情况。编辑:或者它的C#功能的新版本。这将写出12五:

  Dictionary<string, int> test = new Dictionary<string, int>(); 
        test.Add("dave", 12); 
        test.Add("john", 14); 

        int v; 
        test.TryGetValue("dave", out v); 
       { 
          Console.WriteLine(v); 

        } 
+1

正如其他人指出的,您的版本使用此: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/ –

+1

这里是一个小提琴演示它与Roslyn编译器:https://dotnetfiddle.net/eblkGk –

+0

我从来不知道有一个dotnet小提琴。谢谢! –

0

你有任何一个错字或

TryGetValue() 

误会没有必要的代码请阻止您的写入线路位于其中。 只需结束您的代码行并执行writeLine即可。

test.TryGetValue("dave", out int value); // <---- notice the ; 
Console.WriteLine(value); 

编辑:

if test.TryGetValue("dave", out int value) 
{ 
    Console.WriteLine(value); 
} 
0

难道你不想念你的片断的if,都能跟得上: 或者,如Mr.Nimelo暗示,可能if语句缺少像这样是?

Dictionary<string, int> test = new Dictionary<string, int>(); 
    test.Add("dave", 12); 
    test.Add("john", 14); 

    // missing if there? 
    test.TryGetValue("dave", out int value) 
    { 

     Console.WriteLine(value); 

    } 

我的便宜2美分,有点重构...:

var test = new Dictionary<string, int> {{"dave", 12}, {"john", 14}}; 

    if (test.TryGetValue("dave", out var value)) 
    { 
     Console.WriteLine(value); 
    } 

    Console.ReadKey();