Code Contracts warning about possibly failing 'Assume' call

In a class of mine, I have a private field of type ExpandoObject . The field is initialized in the constructior ( this.expected = new ExpandoObject() ), so I'm confident that it will never be null .

Thus, in one of the methods on this class, I fell safe to add

Contract.Assumes(this.expected != null)

before using this.expected for anything, so Code Contracts won't have to worry about possible calls on null objects. However, instead of a warning for possible method call on a null reference, I get a warning saying

The dynamically dispatched call to method 'Assume' may fail at runtime because one or more applicable overloads are conditional method

The method signature and the first few lines of code looks like this:

protected void Expect(object values)
{
    Contract.Requires<ArgumentNullException>(values != null);

    Contract.Assume(this.expected != null);
    var exp = (ICollection<KeyValuePair<string, object>>)this.expected;

On the third line, I get a warning for

CodeContracts: Possibly calling a method on a null reference 'OddEnds.Testing.TestBase.o_SiteContainer0.<>p_Site3.Target'

where I assume the odd signature of the null reference is because exp is a dynamic object.

How do I solve these?


I think the best way to solve your problem is to declare that expected is never null as an invariant on the class:

class TheClass {

    ExpandoObject expected;

    ...

    [ContractInvariantMethod]
    void Invariants()
    {
        Contract.Invariant(this.expected != null);
    }

    ...

}

When you do this, the static checker will check that expected is not null at the end of your constructor, and then it will know that expected is never null at the start of any other method.


我认为下面的代码更改会保持编译器的快乐(如果你肯定在这个演员反正,但为什么使用expandoobject然后......无论如何)

ICollection<KeyValuePair<string, object>> col = this.expected as ICollection<KeyValuePair<string, object>>;
Contract.Assume(col != null);
链接地址: http://www.djcxy.com/p/74408.html

上一篇: 代码合同:确保未经证实和需要未经证实

下一篇: 代码合同警告关于可能失败的'假设'呼叫