我已经创建了这种扩展方法

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 null。为什么 ?

最佳答案

就像其他任何方法一样,对参数的更改不会更改调用方的参数,除非它是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";
}

关于c# - 在扩展方法中创建的实例为null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6896392/

10-11 22:34
查看更多