【发布时间】:2015-02-13 16:41:16
【问题描述】:
我是 Code Contracts 的新手 - 刚开始尝试弄明白。我刚刚遇到了一些我不确定如何完成的事情:
我有一个可以通过属性公开“获取”的私有只读字段:
private readonly string name;
public string Name
{
get
{
return this.name;
}
}
此字段不得为空,不得为空,且不得包含任何空格。所以我在构造函数中放入了各种“Requires”来尝试确保这些东西:
public Thing(string name)
{
Contract.Requires<ArgumentNullException>(
name != null,
"Name must not be null");
Contract.Requires<ArgumentException>(
name.Length > 0,
"Name must have positive length");
Contract.Requires<ArgumentException>(
!name.Any(x => char.IsWhiteSpace(x)),
"Name must not include whitespace");
this.name = name;
}
输入一些代码来尝试违反这些协定表明静态检查器成功地捕获了“not null”和“not empty”的违规行为,但它没有捕获“不包含空格”的违规行为。我想这并不奇怪?我猜它会在编译时进行某些简单的检查(如“!= null”),但其他更复杂的检查(如 linq 检查空格)除了可能在运行时之外没有完成?
不管怎样,我随后在类中添加了一些不变量来尝试描述这些相同的东西:
[ContractInvariantMethod]
private void ContractInvariants()
{
Contract.Invariant(this.name != null);
Contract.Invariant(this.name.Length > 0);
Contract.Invariant(!this.name.Any(x => char.IsWhiteSpace(x)));
}
这导致我的构造函数(上面引用)出现以下警告(至少,警告级别设置为高):
CodeContracts: invariant unproven: !this.name.Any(x => char.IsWhiteSpace(x))
但构造函数将 this.name 设置为需要相同合约的局部变量的值!
我的 Requires 和/或我的 Invariant 没有按照我的意愿去做吗?有没有办法让他们做我打算让他们做的事情?我是否应该试图让他们做我一开始就打算让他们做的事情?我只是从根本上误解了这里的事情吗?就像我说的,我对此完全陌生。感谢您的指导。
【问题讨论】:
-
Contract.ForAll可能值得一试,但我自己在这方面取得的成功有限。
标签: c# .net code-contracts