Skip to main content
 首页 » 编程设计

c#之代码契约问题

2024年02月24日24jyk

考虑以下代码:

public class RandomClass 
{         
    private readonly string randomString; 
 
    public RandomClass(string randomParameter) 
    { 
        Contract.Requires(randomParameter != null); 
        Contract.Ensures(this.randomString != null); 
 
        this.randomString = randomParameter; 
    } 
 
    public string RandomMethod() 
    { 
        return  // CodeContracts: requires unproven: replacement != null 
            Regex.Replace(string.Empty, string.Empty, this.randomString); 
    } 
} 

这确保 randomString 在执行 RandomMethod 时不会为 null。为什么代码契约分析会忽略这个事实并抛出 CodeContracts: requires unproven: replacement != null 警告?

请您参考如下方法:

分析器可能忽略了它无法在两种方法之间建立联系这一事实。

属性“field randomString is non-null”是一个类不变量:它在每个实例创建时建立,并且在每次方法调用时简单地保留,因为该字段是只读的。我敦促你提供一份说明这一点的文件。它很容易被分析器验证,并提供必要的假设来证明 RandomMethod 是安全的。

This page对类不变量有很好的解释。