C# 对于传递给具有约定的方法的null,没有警告。需要

C# 对于传递给具有约定的方法的null,没有警告。需要,c#,code-contracts,C#,Code Contracts,我的目标是静态契约检查以捕获/避免传递空值,我对契约是新手 我用的是合同。要求参数=在方法链接中为null,作为测试,我使用null参数调用它,我希望它会警告我,但它不会 单元测试通过,因此运行时行为符合预期 为什么它不警告我空值将进入不能接受空值的函数 测试类别: using System.Diagnostics.Contracts; public class Link { private readonly Shape origin; private readonly S

我的目标是静态契约检查以捕获/避免传递空值,我对契约是新手

我用的是合同。要求参数=在方法链接中为null,作为测试,我使用null参数调用它,我希望它会警告我,但它不会

单元测试通过,因此运行时行为符合预期

为什么它不警告我空值将进入不能接受空值的函数

测试类别:

using System.Diagnostics.Contracts;

public class Link
{

    private readonly Shape origin;

    private readonly Shape destination;
    public Link(Shape origin, Shape destination)
    {
        Contract.Requires<ArgumentException>(origin != null);
        Contract.Requires<ArgumentException>(destination != null);
        this.origin = origin;
        this.destination = destination;
    }

    public string OriginID()
    {
        return origin.ID;
    }

    public string DestinationID()
    {
        return destination.ID;
    }

}
单元测试:

    using Moq;
    using NUnit.Framework;
    using Simmons.UI.Controls.Diagram;

    namespace Unit
    {
        /// <summary>
        /// A test class for Link
        /// </summary>
        [TestFixture()]
        public class LinkShould
        {
          private Link link;

          [Test()]
          [ExpectedException(typeof(ArgumentException))]
          public void ExplodeWhenLinkIsCreatedWithNulls()
          {
            //set up
            link = new Link(null, null); // No warning on this line
          }    
    }
以下是我在测试项目中的设置:

要使静态检查生效,您需要在“项目属性/代码合同”选项卡中显式启用它们。有一整节都有专门用于配置静态检查的复选框


在您的情况下,请确保为保存链接类的项目启用了该代码。

代码是否为Link Link=new Linknull,null;?你错过了这个例子。是的,举个例子,它应该是。我要改变我的例子。在我的代码中,它是在别处声明的,我忘记了,并忽略了它。它在链接类项目和测试项目中都是这样启用的。