Add a contract for the implementation of the interface

I understand that I cannot add the prerequisites for implementing the interface. I have to create a contract class where I define contracts on the elements that see the interface.

But in the following case, how can I add a contract to the internal state of the implementation, which is therefore not known at the interface definition level?

[ContractClass(typeof(IFooContract))]
interface IFoo
{
  void Do(IBar bar);
}

[ContractClassFor(typeof(IFoo))]
sealed class IFooContract : IFoo
{
  void IFoo.Do(IBar bar)
  {
    Contract.Require (bar != null);

    // ERROR: unknown property
    //Contract.Require (MyState != null);
  }
}

class Foo : IFoo
{
  // The internal state that must not be null when Do(bar) is called.
  public object MyState { get; set; }

  void IFoo.Do(IBar bar)
  {
    // ERROR: cannot add precondition
    //Contract.Require (MyState != null);

    <...>
  }
}
+3
source share
1 answer

You cannot - this postcondition is not suitable for all implementations IFoobecause it is not declared in IFoo. You can access the members of an interface (or other interfaces that it extends).

Foo, , (Ensures), (Requires).

, , :

public void DoSomething(IFoo foo)
{
    // Is this valid or not? I have no way of telling.
    foo.Do(bar);
}

, "" - , , , .

+3

Source: https://habr.com/ru/post/1717004/


All Articles