2017-10-12 67 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();