1

我正在玩微软的 CodeContracts,遇到了一个我无法解决的问题。我有一个有两个构造函数的类:

public Foo (public float f) {
    Contracts.Require(f > 0);
}
public Foo (int i)
    : this ((float)i)
{}

该示例已简化。我不知道如何检查第二个构造函数f是否 > 0。这甚至可以通过合同实现吗?

4

2 回答 2

2

您可以将前提条件添加到第二个构造函数的主体中。

public TestClass(float f)
{
    Contract.Requires(f > 0);
    throw new Exception("foo");
}
public TestClass(int i): this((float)i)
{
    Contract.Requires(i > 0);
}

编辑

尝试调用上面的代码:

TestClass test2 = new TestClass((int)-1);

您将看到在抛出常规异常之前抛出了先决条件。

于 2010-06-18T12:18:23.920 回答
1

我会添加一个静态方法,将 int 转换为 float 并将其包含Contract.Requires在其中。

class Foo
{
    public Foo(float f)
    {
        Contract.Requires(f > 0);
    }

    public Foo(int i) : this(ToFloat(i))
    {
    }

    private static float ToFloat(int i)
    {
        Contract.Requires(i > 0);
        return i;
    }
}

希望这可以帮助。

于 2009-09-12T11:14:16.803 回答