我在使用带有代码约定的不变量时遇到了问题.我想在我的抽象类中定义一个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)