是否可以在C#6.0中创建"自我初始化"字典扩展方法?

Jon*_*nes 2 .net c# extension-methods dictionary c#-6.0

是否可以在Dictionary上创建一个扩展方法,如果Dictionary为null,则能够自我初始化?

我正在考虑以下几点:

public static void AddOrUpdate<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
    // Initialize the Dictionary if null
    dictionary = dictionary ?? new Dictionary<TKey, TValue>();

    // Update or insert value
    dictionary[key] = value;
}
Run Code Online (Sandbox Code Playgroud)

实际使用示例:

// null Dictionary
Dictionary<string, string> dict = null;

// Self-initializing
dict.AddOrUpdate("Key", "Value");
Run Code Online (Sandbox Code Playgroud)

或作为财产:

// Self-initializing
class.nullDict.AddOrUpdate("Key", "Value");
Run Code Online (Sandbox Code Playgroud)

nvo*_*igt 5

没有

为此,您必须传递参数ref,这是不允许的.

this关键字修改静态方法的第一个参数时,它向编译器发出该方法是扩展方法的信号.扩展方法的第一个参数不需要或不允许其他修饰符.