0
我想我在靜態合同檢查工具中發現了一個錯誤。除了用[ContractVerification(false)]
標記整個事物之外,還有其他方法嗎?代碼合同 - 靜態檢查器不會獲得可空類型?
class Employee
{
public int? HierarchyLevel { get; private set; }
public Employee(int? level)
{
Contract.Requires<ArgumentException>(
(!level.HasValue)
||
level >= 0 && level <= 10);
Contract.Ensures(
(!HierarchyLevel.HasValue)
||
(HierarchyLevel.Value >= 0 && HierarchyLevel.Value <= 10));
this.HierarchyLevel = level; //unproven
// this doesnt work either
//if (!level.HasValue) {
// this.HierarchyLevel = new Nullable<int>();
//} else {
// this.HierarchyLevel = new Nullable<int>(level.Value);
//}
// can't even make the static checker shut up with that:
//Contract.Assume(
// (!HierarchyLevel.HasValue)
// ||
// (HierarchyLevel.Value >= 0 && HierarchyLevel.Value <= 10));
}
}
令人驚訝的是,下面的版本工作。但我不想開始編寫單向代碼或引入我自己的Nullable版本來取悅合同驗證工具。
class Employee2
{
public int HierarchyLevel { get; private set; }
public bool HasLevel { get; private set; }
public Employee2(int level, bool hasLevel)
{
Contract.Requires<ArgumentException>(!hasLevel || level >= 0 && level <=10);
if (hasLevel) {
HasLevel = true;
HierarchyLevel = level;
} else {
HasLevel = false;
HierarchyLevel = -1;
}
}
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(
(!HasLevel) ||
(HierarchyLevel >= 0 && HierarchyLevel <= 10));
}
}