Code Contracts [Type]implements interface method {Interface.Method} thus cannot add requires

前端 未结 1 548
你的背包
你的背包 2021-02-18 20:25

I have the following scenario:

public interface ISomething
{
    void DoStuff();
    //...
}

public class Something : ISomething
{
    private readonly ISomethi         


        
1条回答
  •  粉色の甜心
    2021-02-18 20:38

    Explanation

    Section 3: Contract Inheritance of the user manual states that all preconditions must be defined in the root method of an inheritance/implementation chain:

    If a client makes sure that they have satisfied the precondition and has a variable o whose static type is T, then the client should not get a precondition violation when they call o.M. This needs to be true even if the runtime value o has type U. Therefore, the method U.M cannot add a precondition that is stronger than the precondition of T.M.

    While we could allow a weaker precondition, we have found that the complications of doing so outweigh the benefits. We just haven't seen any compelling examples where weakening the precondition is useful. So we do not allow adding any preconditions at all in a subtype.

    As a consequence, method preconditions must be declared on the root method of an inheritance/implementation chain, i.e., the first virtual or abstract method declaration, or the interface method itself.

    Solution

    In your situation, the best course of action is to set up an invariant stating that the _somethingElse field is never null:

    [ContractInvariantMethod]
    private void ObjectInvariant() {
        Contract.Invariant(_somethingElse != null);
    }
    

    This is of course always true, as the field is marked readonly and initialised in the constructor. The static checker isn't able to infer this on its own though, so you must explicitly tell it through that invariant.

    You can optionally add a postcondition Contract.Ensures(_somethingElse != null); to your constructor, but the static checker doesn't require it.

    0 讨论(0)
提交回复
热议问题