Code Contract False Positive and Suppression

I'm starting to use code contracts and trying to clear a false positive warning where code contracts is not recognizing the fact that the dependency property can be set to null and therefore is flagging that the conditional checks are unnecessary. I've attempted to set Contract.Assumes but that seems to enforce only the null case and ignore the non null case which causes it to miss the second contract issue.

How can I suggest to the contracts that both the null and non null cases are possibilities it needs to check?

I have also thought about just suppressing the error but the -outputwarnmasks setting for contract analysis does not give the proper information for me to suppress. It only returns "warning : CodeContracts: warning: The Boolean condition this.Other != null always evaluates to a constant value. If it (or its negation) appear in the source code, you may have some dead code or redundant check" but this does not have the required CheckId value. Where can I get the correct CheckId code if I cannot fix this issue gracefully?

Edit: I still didn't see a CheckId but I did find in the output logs the correct suppression. The suppression notes are not with the warning as I expected but above. I have updated the question code with the correct suppression. I would still consider the suppression a last resort but at least it's an option.

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");
            }
        }
    }
}
链接地址: http://www.djcxy.com/p/23748.html

上一篇: 为什么代码合同声明此代码的“确保为假”?

下一篇: 代码合同虚假肯定和压制