开发者

Why can't contract classes inherit?

开发者_Go百科If I have an interface A and interface B that extends A, can I create a contract class BContract that inherits AContract?

If I try this, I get the following warning:

(1,1): warning CC1066: CodeContracts: Class 'BContract' is annotated as being the contract for the interface 'B' and cannot have an explicit base class other than System.Object.

I haven't tested this yet, but I assume that the implementation of the A interface in BContract is ignored, and the contracts specified in AContract take precedence - in other words I can stub out all methods and properties from A.

I appreciate that it's not a massive inconvenience to do this, but it does seem to lack clarity for anyone looking at BContract. It would save time, space and understanding to be able to derive BContract from AContract, so why is this not supported?


Here's my guess (which I should have thought of before posting) - If interface B extended multiple interfaces - say A and C, with attendant contract classes AContract and CContract - which contract class should BContract inherit from?

There's less ambiguity in always stubbing out base interfaces, rather than mixing up stubs and inheritance of contract classes.


It is supported, but not in the way you're thinking: if interface B derives from interface A, then all the contracts defined on A are also automatically defined for B.

Edit: Here's an example for the comment;

[ContractClass(typeof(IAContracts))]
interface IA
{
    void Foo(int x);
}

[ContractClass(typeof(IBContracts))]
interface IB : IA
{
    void Bar(int y);
}

[ContractClassFor(typeof(IA))]
abstract class IAContracts : IA
{
    public void Foo(int x)
    {
        Contract.Requires(x >= 0);
    }
}

[ContractClassFor(typeof(IB))]
abstract class IBContracts : IB
{
    // inherited from IA
    public abstract void Foo(int x);

    // declared in IB
    public void Bar(int y)
    {
        Contract.Requires(y >= 0);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜