C# CodeContracts不变量为false

C# CodeContracts不变量为false,c#,.net,code-contracts,C#,.net,Code Contracts,VS2010一直告诉我CodeContract.Invariant是假的。我不明白怎么会是这样 public class BankAccountIdentifierDefinitionVariation_CreateCommandArgs : ValidatedCommandArgs { public string IdentifierCode {get; private set; } public string CountryCode {get; private set; }

VS2010一直告诉我CodeContract.Invariant是假的。我不明白怎么会是这样

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...

看起来不变量为false,因为我可以通过其私有setter更改属性的值(即使我不这样做)。有办法解决这个问题吗?属性必须保留为属性,因为我正在序列化。

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


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

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

如果对象是通过其
私有
无参数构造函数构造的,该怎么办?事实并非如此。静态分析器能够看到类的任何部分都不会调用无参数构造函数(并且它不必查找除此之外的其他类)。这就是问题所在,谢谢!