【发布时间】:2014-11-18 11:44:19
【问题描述】:
我有一个Dictionary<string, string> 作为方法参数,我想知道是否有办法让它默认为空字典而不是null。我更喜欢总是有一个空列表/字典/IEnumerable 而不是null。我尝试将参数设置为:
Dictionary<string, string> dictionary = default(Dictionary<string,string>);
但计算结果为null。
有没有办法让默认字典为空?
【问题讨论】:
-
不,你不能。如果您使用可选参数,默认参数的值应该是编译时间常量
-
你的问题有点不清楚.. 为什么不直接使用
if (dictionary == null){ dictionary = new Dictionary<string, string>(); }- 意图很明确,调用者不介意,没有扩展,没有覆盖行为.. 为什么要复杂化?跨度> -
我将“参数”更改为“参数”顺便说一句,我认为这就是你的意思。请参阅What's the difference between an argument and a parameter? 了解区别
-
感谢大家的cmets。我想我会使用空检查或方法重载。我什至问这个问题的原因是我完全同意这篇文章 (blog.mariusschulz.com/2014/07/02/stop-cheating-the-type-system) 和其中的这句话(“如果你返回一个空的 IEnumerable 而不是一个空的,我会来你的房子然后用火箭筒射击你的脸。”)Null 是可能存在的最糟糕的默认值,叹息......
-
任何引用类型的“默认”值为空。默认运算符不知道如何构造对象。您正在寻找的是 null 安全性,并且在 C# 中不存在。
标签: c# dictionary default