使Dictionary方法参数默认为空字典而不是null

Nos*_*nit 4 c# dictionary default

我有一个Dictionary<string, string>方法参数,我想知道是否有办法让它默认为空字典而不是null.我更喜欢总是有一个空的列表/字典/ IEnumerable而不是null.我尝试将参数设置为:

Dictionary<string, string> dictionary = default(Dictionary<string,string>);
Run Code Online (Sandbox Code Playgroud)

但评估结果是null.

有没有办法让默认的Dictionary变空?

Tim*_*ter 9

有没有办法让默认的Dictionary变空?

是的,使用构造函数而不是default:

void Foo(Dictionary<string, string> parameter){
    if(parameter == null) parameter = new Dictionary<string,string>();
}
Run Code Online (Sandbox Code Playgroud)

您还可以使参数可选:

void Foo(Dictionary<string, string> parameter = null)
{
    if(parameter == null) parameter = new Dictionary<string,string>();
}
Run Code Online (Sandbox Code Playgroud)

一个可选的参数必须是一个编译时间常数,这就是为什么你不能使用new Dictionary<string,string>()直接.


根据问题,如果您可以更改default关键字的行为,不,您不能返回不同的值.对于引用类型null是默认值,将返回.

C#语言规范.§12.2:

变量的默认值取决于变量的类型,并确定如下:

  • 对于value-type的变量,默认值与value-type的默认构造函数(第11.1.2节)计算的值相同.
  • 对于reference-type的变量,默认值为null.

更新:对于它的内容,你可以使用这个扩展(我不会使用它):

public static T EmptyIfNull<T>(this T coll) 
    where T :  ICollection, new() // <-- Constrain to types with a default constructor and collections
{
    if(coll == null)
        return new T();
    return coll;
}
Run Code Online (Sandbox Code Playgroud)

现在你可以用这种方式使用它:

Dictionary<string, string> parameter = null;
Foo(parameter.EmptyIfNull());  // now an empty dictionary is passed
Run Code Online (Sandbox Code Playgroud)

但是,另一个程序员想要看到的最后一件事就是成千上万行代码,.EmptyIfNull()因为第一个人懒得使用构造函数.

  • @DanielA.White我不会.你为什么这样?这个答案中的内容非常容易阅读.`parameter = parameter ?? new Dictionary <string,string>();`冗余地将`parameter`的先前值重新分配给自己,让读者想知道为什么会发生这种情况. (3认同)