开发者

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.Requir开发者_运维技巧es<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.


Im thinking following code change will keep compiler happy (if your sure in this cast anyway, but why use expandoobject then.. anyway)

ICollection<KeyValuePair<string, object>> col = this.expected as ICollection<KeyValuePair<string, object>>;
Contract.Assume(col != null);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜