c# - .Net 3.5 使用代码约定实现 String.IsNullOrWhitespace

标签 c# code-contracts conditional-statements

我正在尝试在我的 .Net 3.5 (C#) 项目中使用 Contracts。我发现我在哪里写了类似的东西方法的开始。

我可以将它们留在那里并使用遗留契约(Contract)。我可以将其更改为 Contract.Requires(s!= null && string.IsNullOrEmpty(s.Trim()));。但除了不确定条件的 Whitespace 部分的正确性或性能之外,这些都是蹩脚的(意见)。

相反,我尝试将条件封装在一个方法中以便在契约(Contract)中使用。问题是我仍然无法弄清楚如何以声明方式描述 Whitespace 部分。静态检查器根据我的编写方式发现了几个问题。

我想听听有关数据内容检查的适当性的评论,例如这个检查是否适用于空白以及正确的定义。

public static class str
{
    [Pure]
    public static bool IsNullOrWhitespace(string s)
    {
      Contract.Ensures(s != null || Contract.Result<bool>());
      Contract.Ensures((s != null && !Contract.ForAll<char>(s, c => char.IsWhiteSpace(c))) || Contract.Result<bool>());

      if (s == null) return true;

      for (var i = 0; i < s.Length; i++)
      {
        if (!char.IsWhiteSpace(s, i))
        {
          Contract.Assume(!Contract.ForAll<char>(s, c => char.IsWhiteSpace(c)));
          return false;
        }
      }


      return true;
    }
}

这可能有点草率,但我最初的实验方法就在这里。 a、b 和 c 上的断言失败或未经证实。

static void Test()
{
  string a = null;
  string b = "";
  string c = "     ";
  string d = "xyz";
  string e = "  xyz  ";

  if (!str.IsNullOrWhitespace(a))
  {
    Contract.Assert(a != null);
    a = a.Trim();
  }

  if (!str.IsNullOrWhitespace(b))
  {
    Contract.Assert(b != null && b != "");
    b = b.Trim();
  }

  if (!str.IsNullOrWhitespace(c))
  {
    Contract.Assert(c != null && c != "     ");
    c = c.Trim();
  }

  if (!str.IsNullOrWhitespace(d))
  {
    d = d.Trim();
  }

  if (!str.IsNullOrWhitespace(e))
  {
    e = e.Trim();
  }
}

最佳答案

这是 .NET 4 的内置契约:

Contract.Ensures(
    (Contract.Result<bool>() && ((str == null) || (str.Length == 0)))
    ? ((bool) true)
    : ((Contract.Result<bool>() || (str == null))
      ? ((bool) false)
      : ((bool) (str.Length > 0)))

, null, "Contract.Result<bool>() && (str == null || str.Length == 0) ||\r\n!Contract.Result<bool>() && str != null && str.Length > 0");

尽管它很复杂,但您可以看到其中没有提及空格。我已经尝试了好几次,但我无法找到满足静态检查器要求的东西。

似乎有几个问题阻止我写它,所以我在 Code Contracts 论坛上提出了一些问题。

我的契约(Contract)是:

Contract.Ensures(Contract.Result<bool>() ==
                 (s == null || Contract.Exists(s, char.IsWhiteSpace)))

关于c# - .Net 3.5 使用代码约定实现 String.IsNullOrWhitespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865173/

相关文章:

c# - 如何从 C# 中的多个应用程序配置文件中读取值?

c# - ASP.NET MVC 中的 SQL Server 流文件输出和处理连接

c# - LINQ:C# 中 XML 节点的求和值

c# - 重写期间的 CodeContracts 元数据错误

c# - 代码合约静态分析: Prover Limitations?

具有多个条件的 Java 三元运算符

c# - 如何跟踪表行之间的 ID/ParentID 关系?

c# - 运行时的代码契约

c - 如何在C编程中获得以下输出

javascript - 获取设计中选定文本框的数量