代码合同误报和抑制

时间:2014-11-06 15:34:04

标签: c# code-contracts

我开始使用代码契约并尝试清除误报警,其中代码契约没有认识到依赖属性可以设置为null,因此标记条件检查是不必要的。我试图设置Contract.Assumes,但这似乎只强制执行null情况并忽略非null情况,导致它错过第二个合同问题。

我如何向合同建议null和非null案例都是需要检查的可能性?

我还考虑过只是抑制错误,但合同分析的-outputwarnmasks设置没有为我提供适当的信息来抑制。它只返回“警告:CodeContracts:warning:布尔条件this.Other!= null总是求值为常量值。如果它(或它的否定)出现在源代码中,你可能会有一些死代码或冗余检查”但是这没有所需的CheckId值。如果我不能优雅地解决这个问题,我在哪里可以获得正确的CheckId代码?

编辑:我仍然没有看到CheckId,但我确实在输出日志中找到了正确的抑制。抑制笔记不是我预期的警告,而是上面的警告。我已使用正确的抑制更新了问题代码。我仍然认为抑制是最后的手段,但至少它是一种选择。

using System;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;
using System.Diagnostics.CodeAnalysis;

namespace WpfContractExamples
{
    public class ExampleBehavior : Behavior<FrameworkElement>
    {
        public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExampleBehavior), new UIPropertyMetadata(null));

        public ICommand Command {  get { return (ICommand)GetValue(CommandProperty);  } set { SetValue(CommandProperty, value); } }

        public static readonly DependencyProperty OtherProperty = DependencyProperty.Register("Other", typeof(string), typeof(ExampleBehavior), new UIPropertyMetadata("Anything"));

        public InputGesture Other { get { return (InputGesture)GetValue(OtherProperty); } set { SetValue(OtherProperty, value); } }

        [SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant", Justification = "Command can be null from binding")]
        void AssociatedObject_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //Contract.Assume(Command == null);
            if (Other.Matches(sender, e) && Command != null)
            {
                if(Other != null)
                    Console.WriteLine("Not Null");
            }
        }
    }
}

0 个答案:

没有答案