小编Dyn*_*ike的帖子

代码契约:抽象类中的不变量

我在使用带有代码约定的不变量时遇到了问题.我想在我的抽象类中定义一个Invariant,但它只是被忽略了.下面的代码显示了我的界面和抽象类.

[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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

    private int _x;
    public int X
    {
        get …
Run Code Online (Sandbox Code Playgroud)

c# abstract-class invariants code-contracts

9
推荐指数
1
解决办法
527
查看次数

标签 统计

abstract-class ×1

c# ×1

code-contracts ×1

invariants ×1