我得到以下代码:
public IEnumerator<TRow> GetEnumerator()
{
if (this._rows.Values == null) return Enumerable.Empty<TRow>().GetEnumerator();
return this._rows.Values.GetEnumerator();
}
Resharper告诉我_rows.Values始终为非null(不是这种情况,因为我使用IDictionary的实现-从此处http://doc.postsharp.net/t_postsharp_patterns_collections_advisabledictionary_2的PostSharps
AdvisableDictionary
)在创建后往往会返回null(我猜这很尴尬的实现-我不知道为什么他们会这样实现)。无论我使用哪种IDictionary实施-ReSharper为什么期望该实施以这种方式工作?没有人可以保证这是真的。还是我做错了什么?
如注释中所述:显示行为的最小实现(在
return Enumerable.Empty<TRow>().GetEnumerator()
上设置一个断点,由resharper变灰): class Program
{
static void Main(string[] args)
{
var model = new Model();
bool any = model.Any();
}
}
[NotifyPropertyChanged]
public class Model : IEnumerable<string>
{
private IDictionary<string, string> dictionary;
public Model()
{
dictionary = new AdvisableDictionary<string, string>();
}
public IEnumerator<string> GetEnumerator()
{
if (dictionary.Values == null) return Enumerable.Empty<string>().GetEnumerator();
return dictionary.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
此示例需要
PostSharp.Patterns.Model
程序包和PostSharp许可证(有试用版),或者将AdvisableDictionary
交换为自定义词典,该词典在Values
吸气剂上返回null。 最佳答案
Microsoft在较新的referencesource中添加了一些覆盖IDictionary<,>
的代码合同:
// Returns a collections of the values in this dictionary.
ICollection<TValue> IDictionary<TKey, TValue>.Values {
get {
Contract.Ensures(Contract.Result<ICollection<TValue>>() != null);
return default(ICollection<TValue>);
}
}
从此合同中可以很明显地看出,
Values
一定不能是null
(请注意,它是一个mustn't
,而不是一个can't
:-) IDictionary<,>
的已损坏实现可以返回null
并赢得不会被运行时捕获)。