假設以下簡單的代碼:接口契約混淆靜態檢查
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