假设我有以下类层次结构:
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)
{
}
}
当我编译时,我得到以下 Foo
的 CodeContracts 错误:
Error 12 CodeContracts: Missing precondition in an externally visible method. Consider adding Contract.Requires(obj != null); for parameter validation
有没有办法让 CodeContracts 认识到验证已经发生在基类中?
最佳答案
不幸的是没有。 您的 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);
}
}
将是解决此问题的唯一方法。
关于c# - CodeContracts 错误地标记了基础构造函数中已经存在的缺失前提条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30478071/