具有构建器模式的 C# 代码契约 - "Possibly calling a method on a null reference"

C# Code Contracts with Builder Pattern - "Possibly calling a method on a null reference"

我正在研究代码契约,我正在像这样实现构建器模式:

public class PersonCaution
{
    private PersonCaution()
    {
    }

    public string CautionType { get; private set; }
    public string Remarks { get; private set; }

    public class Builder
    {
        private string _cautionType;
        private string _remarks;

        public Builder WithCautionType(string value)
        {
            Contract.Ensures(Contract.Result<Builder>() != null);

            _cautionType = value;                
            return this;
        }

        public Builder WithRemarks(string value)
        {
            Contract.Ensures(Contract.Result<Builder>() != null);

            _remarks = value;
            return this;
        }

        public PersonCaution Build()
        {
            Contract.Ensures(Contract.Result<PersonCaution>() != null);

            return new PersonCaution
            {
                CautionType = _cautionType,
                Remarks = _remarks
            };
        }
    }
}

下面是一个显示我如何使用生成器的片段 class:

if (row != null)
{
    var builder = new PersonCaution.Builder()
        .WithCautionType((string)row.Element("PersonCaution__Type1G"))
        .WithRemarks((string)row.Element("PersonCaution__Remarks"));

    if (builder != null)
    {
        personCautions.Add(builder.Build());
    }
}

但是,代码契约静态检查器失败并出现此错误:

Possibly calling a method on a null reference. Do you expect that NWP.PointServices.Domain.Model.People.PersonCaution+Builder.WithCautionType(System.String) returns non-null?

问。我认为 Contract.Ensures 后置条件会满足静态检查器的要求,但事实并非如此。我需要做什么来消除错误?非常感谢。

注。如果 Builder class 位于调用它的代码的单独项目中,我只会看到问题。

更多信息:

正如我们所发现的,您只需要从 CC 项目选项卡启用合同引用的构建即可启用跨项目分析 ("Contract Reference Assembly" = "Build")