【问题标题】:Explanation of Pre-conditions and Post-Conditions?前置条件和后置条件的解释?
【发布时间】:2014-08-24 05:54:45
【问题描述】:

我最近的任务要求我有这个遵循标准

"所有方法都有显式后置条件和带参数的方法 先决条件“

我已经阅读了一些试图解释前置/后置条件的网页,但似乎掌握了它们,有人可以向我解释它们是什么,它们的用途以及如何编写它们吗?

谢谢

(顺便说一下我学的语言是C#)

【问题讨论】:

  • public static int GetStringLength(string str) { if (str == null) throw new ArgumentNullException("str", "y u no respect preconditions???"); ... }。如果你有一些前置条件和后置条件的框架,你可能还会有 [NotNull] string str 之类的注释。

标签: c# post-conditions


【解决方案1】:

进入方法前前提条件必须为真,否则合约无效。 退出方法后,后置编码应该为真。 对不起,我不懂 C#,但如果你知道 Java,这个选择排序示例可能会有所帮助。 示例:

public static void selSort(int[] a, int b) {
    //Pre-condition: array a is not null and size of unsorted section is bigger than 1.
    for(int unsortSz = b; unsortSz >1; unsortSz--) {
        int max = 0;
        for (int p = 1; p < unsortSz; p++){
            if (a[p] > a[max]){
                max = p;
            }
        }

        //Post-condition: max is the position of largest element in unsorted part. 

        // now just swap the last element in unsorted part with max
        temp = a[unsortSz-1];
        a[unsortSz] = a[max];
        a[max] = temp;
    }
}

【讨论】:

    【解决方案2】:

    这都是代码契约的一部分。输入方法或属性时,应满足先决条件。而后置条件是方法或属性代码退出时的期望。来自MSDN

    前提条件指定调用方法时的状态。他们是 通常用于指定有效的参数值。所有成员 前提条件中提到的必须至少与 方法本身;否则,前提条件可能无法理解 方法的所有调用者。

    后置条件是方法终止时的状态契约。在退出方法之前检查后置条件。 失败的后置条件的运行时行为由 运行时分析器。

    也可以查看这篇优秀的文章Preconditions, Postconditions: Design by Contract for C#

    【讨论】:

    • 第二个链接坏了
    【解决方案3】:

    调用方法之前的条件称为前置条件,如方法名称、参数类型和参数数量等。后置条件是方法末尾的条件,如返回类型为 float 的方法必须返回浮点数而不是 int 等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多