CodeContracts - 误报

Jud*_*ngo 5 c# code-contracts

我刚开始在一个现有的中型项目上尝试使用.NET 4中的CodeContracts,我很惊讶静态检查器给出了关于以下代码段的编译时警告:

public class Foo
{
   private readonly List<string> strs = new List<string>();

   public void DoSomething()
   {
       // Compiler warning from the static checker:
       // "requires unproven: source != null"
       strs.Add("hello");
   }
}
Run Code Online (Sandbox Code Playgroud)

为什么CodeContracts静态检查器抱怨strs.Add(...)行?strs没有可能成为null的方法,对吗?难道我做错了什么?

Ric*_*ich 8

可以标记该字段readonly,但遗憾的是静态检查器对此不够智能.因此,由于静态检查器无法自行推断strs永远不为null,因此必须通过不变量明确告知它:

[ContractInvariantMethod]
private void ObjectInvariant() {
    Contract.Invariant(strs != null);
}
Run Code Online (Sandbox Code Playgroud)

  • 公平地说,即使是只读字段也可以通过反射来设置,所以事实上,`strs`*CAN*是'null` (2认同)