代码合同:抽象类中的不变量 [英] Code Contracts: Invariants in abstract class

查看:154
本文介绍了代码合同:抽象类中的不变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在将不变式与代码约定一起使用时遇到问题。
我想在我的抽象类中定义一个不变式,但是它只是被忽略了。下面的代码显示了我的界面和抽象类。

I have encountered a problem while using Invariants with Code Contracts. I want to define an Invariant within my abstract class but it is simply ignored. The code below shows my interface and the abstract class.

[ContractClass(typeof(IPointContract))]
interface IPoint
{
    int X { get; }
    int Y { get; }
}

[ContractClassFor(typeof(IPoint))]
abstract class IPointContract : IPoint
{

    public int X
    {
        get { return 0; }

    }

    public int Y
    {
        get { return 0; }
    }

    [ContractInvariantMethod]
    private void PointInvariant()
    {
        Contract.Invariant(X > Y);
    }
}

然后,我在Point类中实现此接口,并从中创建一个对象。这至少应该在运行时失败。

Afterwards, I implement this interface within my Point class and create an object from it. This should at least fail during runtime.

class Point : IPoint
{
    public Point(int X, int Y)
    {
        this._x = X;
        this._y = Y;
    }

    private int _x;
    public int X
    {
        get { return _x; }
    }

    private int _y;
    public int Y
    {
        get { return _y; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Point p = new Point(1, 2);
    }
}

当我将不变式移至Point-Class时,它工作正常。

When I move the Invariant to the Point-Class, it works fine. All other pre- or post conditions are working fine too.

是否不可能在抽象类中包含不变式?或者我做错了吗?

Is it not possible to have Invariants within an abstract class or am I doing it wrong?

推荐答案

接口不支持不变式。 (您的问题标题是抽象类中的不变式,但问题的关键在于接口。)

Invariants are not supported on interfaces. (Your question title is "Invariants in abstract class" but the crux of the problem is with the interface.)

我的猜测是这是因为不变式需要状态但需要接口没有状态。我确信代码合同团队可以解决此问题,我希望他们会这样做,因为这将是一个很棒的功能。

My guess is that this is because invariants require state but interfaces don't have state. I'm sure the code contracts team can work around this and I wish they would because this would be a great feature to have.

要解决此限制,您可以:

To work around this limitation you could:


  • 将不变方法添加到派生类中( Class Point 等) 。

  • 或者,将setter添加到抽象类属性中,并在setter中实现合同逻辑。

  • Add the invariant method to the derived classes (class Point, etc.).
  • Or, add setters to the abstract class properties and implement the contract logic in the setters.

这篇关于代码合同:抽象类中的不变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆