假设以下简单的代码:接口契约混淆静态检查
public class Foo // : IFoo
{
private string _field;
public string Property
{
get { return _field; }
}
private void SetField()
{
_field = " foo ";
}
private string Method()
{
SetField();
return Property.Trim();
}
}
的静态检查是能证明Property
将不为空时Method
使用它。现在
,我介绍一个接口与合同一起和静态检查开始抱怨:“可能调用空引用‘this.Property’的方法
这是一个错误还是我失去了一些东西?
与接口的代码如下所示:
public class Foo : IFoo
{
private string _field;
public string Property
{
get { return _field; }
}
private void SetField()
{
_field = " foo ";
}
private string Method()
{
SetField();
return Property.Trim();
}
}
[ContractClass(typeof(IFooContract))]
public interface IFoo
{
string Property { get; }
}
[ContractClassFor(typeof(IFoo))]
public abstract class IFooContract : IFoo
{
public string Property
{
get { throw new System.NotImplementedException(); }
}
}
我的设置都像第是:
我得到以下输出:
[...]
C:\{path}\CC2.cs(11,19): message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.Result<System.String>() == this._field);
C:\{path}\CC2.cs(16,13): message : CodeContracts: Suggested ensures: Contract.Ensures(this._field != null);
C:\{path}\CC2.cs(21,13): message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.Result<System.String>() != null);
C:\{path}\CC2.cs(21,13): message : CodeContracts: Suggested ensures: Contract.Ensures(this._field != null);
C:\{path}\CC2.cs(21,13): message : CodeContracts: Suggested ensures: Contract.Ensures(this.Property.Trim() != null);
C:\{path}\CC2.cs(21,13): message : CodeContracts: Suggested ensures: Contract.Ensures(Contract.Result<System.String>() == this.Property.Trim());
[...]
C:\{path}\CC3.cs(33,13): warning : CodeContracts: Possibly calling a method on a null reference 'this.Property'
[...]
我使用Visual Studio 2010旗舰版和.NET 4的目标框架。
我不能用VS 2012和VS 2010分别用C#5和4编译来重现它。我有相同的代码合同版本和配置。我只收到8个建议保证。我错过了什么吗? – 2013-02-19 16:48:01
@IlyaIvanov:你编译了第一个或第二个代码片段吗?只有第二个片段显示该行为。此外,请确保您的设置与我的设置相同。 – 2013-02-19 16:50:41
我确定,所有的都是一样的。此外,如果我评论'//SetField();'然后我收到'CodeContracts:可能调用空引用方法'this.Property'' – 2013-02-19 16:51:35