我正在尝试在我的 .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()));
。但除了不太确定其正确性或性能之外空白作为条件的一部分,这些都是蹩脚的(意见)。
相反,我尝试将条件封装在合同中使用的方法中。问题是我还是不知道如何描述空白部分声明式。静态检查器会根据我的编写方式发现几个问题。
我想听听有关数据内容检查是否适当的评论,例如针对空格以及正确定义的检查。
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();
}
}