6

我正在使用 MS Code Contracts,并且在使用接口继承和 ContractClassFor 属性时遇到了麻烦。

给定这些接口和合约类:

[ContractClass(typeof(IOneContract))]
interface IOne { }
[ContractClass(typeof(ITwoContract))]
interface ITwo : IOne { }

[ContractClassFor(typeof(IOne))]
abstract class IOneContract : IOne { }
[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : IOneContract, ITwo { }

假设 IOne 和 ITwo 是实体接口。因此 IOneContract 将包含大量代码以进行必要的检查。

我不想在 IOne 接口的 ITwoContract 中复制所有这些内容。我只想为 Itwo 接口添加新合同。从另一个合同类继承一个合同类似乎是重用该代码的可能方式。但是我收到以下错误:

EXEC : warning CC1066: Class 'ITwoContract' is annotated as being the contract for the interface 'ITwo' and cannot have an explicit base class other than System.Object.

这是代码合同的限制还是我做错了?我们的项目中有很多接口继承,如果我不知道如何解决这个问题,这感觉就像代码合同的交易破坏者。

4

1 回答 1

10

代替:

[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : IOneContract, ITwo { }

只需继承合同:

[ContractClassFor(typeof(ITwo))]
abstract class ITwoContract : ITwo { }

您只需要提供关于ITwo. 合同 fromIOneContract将自动继承,您可以将所有继承的IOne方法声明为抽象 - 事实上,您不能IOne为on提供合同ITwoContract,否则 CC 会抱怨:)

例如,如果你有这个:

[ContractClass(typeof (IOneContract))]
interface IOne
{
    int Thing { get; }
}

[ContractClass(typeof (ITwoContract))]
interface ITwo : IOne
{
    int Thing2 { get; }
}

[ContractClassFor(typeof (IOne))]
abstract class IOneContract : IOne
{
    public int Thing
    {
        get
        {
            Contract.Ensures(Contract.Result<int>() > 0);
            return 0;
        }
    }
}

[ContractClassFor(typeof (ITwo))]
abstract class ITwoContract : ITwo
{
    public int Thing2
    {
        get
        {
            Contract.Ensures(Contract.Result<int>() > 0);
            return 0;
        }
    }

    public abstract int Thing { get; }
}

然后这个实现将在这两种方法上都说“未经证实的合同”,正如预期的那样:

class Two : ITwo
{
    public int Thing
    {
        get { return 0; }
    }

    public int Thing2
    {
        get { return 0; }
    }
}
于 2010-07-08T04:58:24.723 回答