com*_*cme 4 c# generics collections resharper
我正在使用a Dictionary<string, string>并添加一个空值的项目(在我的实际情况下它是一个变量).
var testDictionary = new Dictionary<string, string>();
testDictionary.Add("Test", null);
Run Code Online (Sandbox Code Playgroud)
这导致警告"可能'null'赋值给标记为'NotNull'属性的实体".

如果我让ReSharper将其转换为Collection Initializer,它不会显示任何警告.
var testDictionary = new Dictionary<string, string> {{"Test", null}};
Run Code Online (Sandbox Code Playgroud)
那么,字典的值是否用'NotNull'属性标记是真的吗?或者还有其他事情发生了吗?
编辑:这个问题与Resharper没有太大区别:可能对使用notnull属性标记的实体进行null赋值,但是我的问题的答案是不同的(这是R#中的一个错误,并且将null元素添加到集合中并不是一个好处理念).
通常,将null元素放入集合中是一种不好的做法.绝大多数使用集合的代码都假定集合中的值不是null.如果null是有效的集合元素,它确实使所有消费代码复杂化.
例如,你基本上需要写
foreach (var cur in theCollection) {
if (cur.Value == null) {
continue;
}
...
}
Run Code Online (Sandbox Code Playgroud)
对于这种特定情况,它看起来像R#缺少集合初始化器案例.null在收藏中绝对是意料之外的.
而不是null为什么不使用String.Empty?