我正在尝试在我的 .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/