3

假设我有以下类层次结构:

public class FooBase
{
    private readonly object _obj;

    protected FooBase(object obj)
    {
        Contract.Requires(obj != null);
        _obj = obj;
    }
}

public class Foo : FooBase
{
    public Foo(object obj) : base(obj)
    {
    }
}

编译时,我收到以下 CodeContracts 错误Foo

Error   12  CodeContracts: Missing precondition in an externally visible method. Consider adding Contract.Requires(obj != null); for parameter validation

有没有办法让 CodeContracts 认识到验证已经在基类中发生?

4

1 回答 1

0

不幸的是没有。您的 Foo 在没有适当要求的情况下调用 FooBase(obj) 。

public class FooBase
{
    private readonly object _obj;

    protected FooBase(object obj)
    {
        Contract.Requires(obj != null);
        _obj = obj;
    }
}

public class Foo : FooBase
{
    public Foo(object obj) : base(obj)
    {
        Contract.Requires(obj != null);
    }
}

将是解决此问题的唯一方法。

于 2015-11-04T21:32:19.587 回答