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)
| 归档时间: |
|
| 查看次数: |
623 次 |
| 最近记录: |