次の単純なコードを想定します。
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
静的チェッカーは、使用時に null ではないことを証明できますMethod
。
ここで、コントラクトと共にインターフェイスを導入すると、静的チェッカーが「null 参照 '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'
[...]
.NET 4 をターゲット フレームワークとして Visual Studio 2010 Ultimate を使用しています。