CodeContracts不变量为false

本文关键字:false 不变量 CodeContracts | 更新日期: 2023-09-27 17:58:52

VS2010一直告诉我CodeContract.Invariant是false。我看不出怎么会出现这种情况

public class BankAccountIdentifierDefinitionVariation_CreateCommandArgs : ValidatedCommandArgs
{
    public string IdentifierCode {get; private set; }
    public string CountryCode {get; private set; }
    public Ems.Infrastructure.Validation.StringValidator Validator {get; private set; }
    private BankAccountIdentifierDefinitionVariation_CreateCommandArgs()
        : base() { }
    public BankAccountIdentifierDefinitionVariation_CreateCommandArgs(
        string identifierCode,
        string countryCode,
        Ems.Infrastructure.Validation.StringValidator validator)
    {
        Contract.Requires(!string.IsNullOrEmpty(identifierCode));
        Contract.Requires(!string.IsNullOrEmpty(countryCode));
        Contract.Ensures(!string.IsNullOrEmpty(this.IdentifierCode));
        Contract.Ensures(!string.IsNullOrEmpty(this.CountryCode));
        this.IdentifierCode = identifierCode;
        this.CountryCode = countryCode;
    }
    [ContractInvariantMethod]
    void ContractInvariants()
    {
        Contract.Invariant(!string.IsNullOrEmpty(IdentifierCode));
        Contract.Invariant(!string.IsNullOrEmpty(CountryCode));
    }
}

警告是,这两个不变量都是false,显然情况并非如此。我还尝试了以下两种变体。

Contract.Ensures(!string.IsNullOrEmpty(this.IdentifierCode);
if (string.IsNullOrEmpty(identifierCode)) throw new ArgumentNullException...
this.IdentifierCode = identifierCode;

以及

Contract.Ensures(!string.IsNullOrEmpty(this.IdentifierCode));
this.IdentifierCode = identifierCode;
if (string.IsNullOrEmpty(this.IdentifierCode)) throw new ArgumentNullException...

看起来不变量是假的,因为我可以通过它的私有setter来更改属性的值(尽管我没有。)有办法解决这个问题吗?属性必须保持为属性,因为我正在序列化。

CodeContracts不变量为false

静态分析器似乎没有看到从未调用过无参数构造函数。也许它的存在足以质疑你的不变量。

你能把它全部去掉吗?如果你已经有了一个构造函数,为什么你需要一个私有的无参数构造函数?

我希望私有默认构造函数是警告的来源,因为执行它确实会违反不变量。然而,由于您已经定义了构造函数,因此没有什么可以阻止您删除默认构造函数。如果您定义了至少一个构造函数,编译器将不会代表您发出默认构造函数,并且由于您从未使用过默认构造函数,因此没有理由将其放在首位