2011-08-01 103 views
2

我創造了這個擴展方法創建的實例是空

public static void AddIfNullCreate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) 
{ 
    if (dictionary == null) 
    { 
     dictionary = new Dictionary<TKey, TValue>(); 
    } 

    dictionary.Add(key, value); 
} 

但是當我用它

public void DictionaryTest() 
    { 
     IDictionary<int, string> d = GetD(); 

     d.AddIfNullCreate(1,"ss"); 
    } 

    private IDictionary<int, string> GetD() 
    { 
     return null; 
    } 

調用後AddIfNullCreate是d空。爲什麼 ?

回答

8

就像任何其他方法,改變到參數不除非它是一個ref參數(它不能成爲擴展方法第一個參數)改變呼叫者的論點The argument is passed by value,即使該值是參考。

一種選擇是返回字典太:

public static IDictionary<TKey, TValue> AddIfNullCreate<TKey, TValue> 
    (this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) 
{ 
    if (dictionary == null) 
    { 
     dictionary = new Dictionary<TKey, TValue>(); 
    } 

    dictionary.Add(key, value); 
    return dictionary; 
} 

然後:

d = d.AddIfNullCreate(1, "ss"); 

但是,我不知道我真正做到這一點。我想我只是有條件地創建方法本身的詞典:

public void DictionaryTest() 
{ 
    IDictionary<int, string> d = GetD() ?? new Dictionary<int, string>(); 

    d[1] = "ss"; 
} 
+0

喬恩在這裏,沒有什麼可以像往常一樣添加:) +1 –

3

如果這是作爲一個正常的方法來完成你需要把字典作爲參考參數,以便存儲指向新創建的對象設置正確。儘管如此,我不認爲你可以將擴展方法的第一個參數指定爲ref參數。