我可以在框架方法上使用SuppressMessage吗?

时间:2011-12-22 20:02:05

标签: c# code-contracts suppressmessage

我想从CodeContracts实施以下建议:

CodeContracts: MyModule: Method MyModule.MyClass.MyMethod: 
To mask *all* warnings issued like the precondition add the attribute: 

[SuppressMessage("Microsoft.Contracts", "RequiresAtCall-propertyAccessor != null")] 

to the method 

System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression,System.Reflection.MethodInfo)

感觉我应该能够使用具有Target属性的SupressMessage来实现这一点。但是,因为这是 Framework 方法,我不确定。

//doesn't work
[module: SuppressMessage("Microsoft.Contracts", "RequiresAtCall-propertyAccessor != null", Scope = "Member", Target = "System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression,System.Reflection.MethodInfo)", Justification = "This isn't covered by Linq Contracts yet.")]

如何全局抑制此警告,以便我不必基线或抑制所有呼叫站点警告?

EDIT: The specific usage that requires this measure is:

void mymethod()
{
    var myObserver = new PropertyObserver<MyViewModel>();
    //this line throws the error, within the n => n.Value expression
    myObserver.RegisterHandler(n => n.Value, OnValueChanged);
}

public class PropertyObserver<TPropertySource> where TPropertySource : INotifyPropertyChanged
{
    public PropertyObserver<TPropertySource> RegisterHandler(
        Expression<Func<TPropertySource, object>> expression,
        Action<TPropertySource> handler)
    {
        //what this does is irrelevant; the violation  occurs in the method call
    }
}

//n => n.Value decompiles to the following
public static MemberExpression Property (Expression expression, MethodInfo   propertyAccessor)
{
    //and this line is the message I want to suppress, but it's in the .NET framework.
    ContractUtils.RequiresNotNull(propertyAccessor, "propertyAccessor");
    ValidateMethodInfo(propertyAccessor);
    return Property (expression, GetProperty(propertyAccessor));
}

4 个答案:

答案 0 :(得分:3)

在使用ranomore进行更多调查之后,代码合同中似乎存在一个错误。

通过n => n.Value访问的类具有通用T Value属性。如果将类更改为非泛型类(使用object Value),则警告将消失。 (带有object Value的通用类也会发出警告)。

当然,这并没有回答原来的问题,但我认为不可能这样做。

答案 1 :(得分:0)

  1. 将GlobalSuppressions.cs添加到项目的根目录。

  2. 添加[模块...

  3. 用程序集替换单词模块。

  4. 这有用吗?

答案 2 :(得分:0)

它确实有效。您可以向包含表达式的方法添加SupressMessageAttribute。只是不要使用RequiresAtCall。相反,请使用Requires

[SuppressMessage("Microsoft.Contracts", "Requires",
                 Justification = "Bug in static checker")]
public void Override(AutoMapping<Bookings> mapping)
{
    Contract.Assume(mapping != null);

    mapping.Id(x => x.Id);
}

明显的缺点是你必须使用这些代码来填充代码......

答案 3 :(得分:-1)

查看项目属性的“构建”选项卡。有一个“抑制警告”字段。

/nowarn (C# Compiler Options)