0

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));
    }
}

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

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

看起来好像不变量是错误的,因为我可以通过其私有设置器更改属性的值(即使我没有。)有没有办法解决这个问题?属性必须保留属性,因为我正在序列化。

4

2 回答 2

2

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

可以完全删除吗?如果您已经有一个构造函数,为什么还需要一个私有的无参数构造函数?

于 2013-02-13T11:41:46.070 回答
0

I would expect the private default constructor to be the source of the warning, since executing that would indeed violate the invariant. However since you have a constructor defined there's nothing stopping you from deleting the default constructor. If you define at least one constructor the compiler will not emit a default contructor on your behalf and since you are never using the default constructor there's no reason to have it in the first place

于 2013-02-13T11:47:32.617 回答