C# 代码契约(Contract) : Why can't this simple condition be proven?

标签 c# code-contracts

我正在对代码契约进行简单测试。以下代码是在 winform 中。这通过了(当然):

    private void Test(Form form)
    {
        Contract.Requires(!string.IsNullOrEmpty(form.Name));

        MessageBox.Show(form.Name);
    }

    protected override void OnLoad(EventArgs e)
    {
        if (!string.IsNullOrEmpty(Name))
            Test(this);

        base.OnLoad(e);
    }

但是,我只添加了一个非常简单的间接级别,它说“需要未经证实”:

    private bool Valid(string str)
    {
        return !string.IsNullOrEmpty(str);
    }

    protected override void OnLoad(EventArgs e)
    {
        if (Valid(Name))
            Test(this);

        base.OnLoad(e);
    }

这似乎很容易证明。为什么它不起作用?

最佳答案

您的 Valid 方法没有任何契约。您可以在那里表达契约(Contract),这可能与代码相同,真的……但代码契约(Contract)不会假设这一点。您的实现可能会发生变化 - 您没有告诉 Code Contracts 该方法意味着要做什么,因此它不会从实现中假设任何东西。

关于C# 代码契约(Contract) : Why can't this simple condition be proven?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3517574/

相关文章:

c# - 如何解决这个 :The URI prefix is not recognized

c# - 如何在 asp.net core blazor 的通用服务中使用任何模型

c# - 如何在 Silverlight 中序列化派生类

c# - 代码契约和异步

.net - 在调用例程之后和之前在哪里评估不变量?

c# - 不使用ccrewrite,“Contract.Requires <T>”的行为如何?这与“要求”有所不同吗?

c# - 使用 Microsoft Cognitive Speech + Websocket 的连续语音识别 - Xamarin

c# - 如何反序列化然后将数据放入表格?

c# - 如何从代码契约(Contract)中自动生成建议的要求?

code-contracts - 删除 Visual Studio 2017 中的代码契约(Contract)