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变空?
有没有办法让默认的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:
变量的默认值取决于变量的类型,并确定如下:
更新:对于它的内容,你可以使用这个扩展(我不会使用它):
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()因为第一个人懒得使用构造函数.