2013-08-02 62 views
0

爲了彙總某些特定值的出現次數,我使用了dictionary<valueName:string, counter:int>,我完全不知道這些值。 所以我寫了一個方法SetOrIncrement,據稱是用來像彙總字典

myDictionary.SetOrIncrement(name, 1); 

但是,VisualStudio的grumbls

「字典中不包含定義 ‘SetOrIncrement’,沒有擴展方法「 SetOrIncrement'接受一個 類型'字典的第一個參數可以找到。「

有誰能告訴我是什麼原因?

這裏的SetAndIncrement方法:

public static class ExtensionMethods 
{ 
    public static int SetOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int set) { 
     int value; 
     if (!dict.TryGetValue(key, out value)) { 
      dict.Add(key, set); 
      return set; 
     } 
     dict[key] = ++value; 
     return value; 
    } 
} 
+0

您是否在您嘗試使用擴展方法的代碼中包含了擴展方法的名稱空間? –

+0

不,但使用擴展方法的類位於相同的名稱空間中。 'namespace test {class user {...} public static class ExtensionMethods {...}} – Explicat

+0

如果字典關鍵字已經存在,您是否真的很感興趣,以便忽略set的值,並依次遞增值你的意思是做一個'+ = set'嗎?在某些情況下忽略參數似乎很奇怪...... – Chris

回答

1

貴擴展方法正確編譯?當我嘗試編譯它時,我得到:「類型參數聲明必須是標識符而不是類型」。

的原因是,在這條線:

public static int SetOrIncrement<TKey, int>(this Dictionary<TKey, int> dict, TKey key, int set) { 

在該方法的泛型參數的int無效。相反,這應該工作:

public static int SetOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int set) { 

原因是,TKey是變化的唯一類型。 int總是相同的,所以不是通用參數。

1

試試這個:

void Main() 
{ 
    var dict = new Dictionary<string, int>(); 
    dict.SetOrIncrement("qwe", 1); 
} 

// Define other methods and classes here 
public static class ExtensionMethods 
{ 
    public static int SetOrIncrement<TKey>(this Dictionary<TKey, int> dict, TKey key, int set) 
    { 
     int value; 
     if (!dict.TryGetValue(key, out value)) { 
      dict.Add(key, set); 
      return set; 
     } 
     dict[key] = ++value; 
     return value; 
    } 
} 
+0

謝謝,就是這樣! – Explicat