簡體   English   中英

.Net 3.5使用代碼協定實現String.IsNullOrWhitespace

[英].Net 3.5 Implementation of String.IsNullOrWhitespace with Code Contracts

我正在嘗試在.Net 3.5(C#)項目中使用合同。 我發現我在哪里寫過類似if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(s.Trim())) throw new ArgumentException("Required", "s"); 在方法開始時。

我可以將其保留在那里並使用舊合同。 我可以將其更改為Contract.Requires(s!= null && string.IsNullOrEmpty(s.Trim())); 但是除了對條件的空白部分的正確性或性能不是很確定之外,這些都是la腳的(意見)。

相反,我嘗試將條件封裝在可用於合同的方法中。 問題是我仍然不知道如何聲明性地描述空白部分。 靜態檢查器會根據我的編寫方式找到幾個問題。

我想聽聽有關數據內容檢查是否適當的評論,例如針對空格AS WELL AS的正確定義。

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");

盡管它很復雜,但您可以看到沒有提及空格。 我已經嘗試了幾次,但是無法滿足靜態檢查器的要求。

似乎有一些問題使我無法編寫它,因此我在“代碼合同”論壇上提出了一些問題。

我的合同是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM