【发布时间】:2011-12-22 20:02:05
【问题描述】:
我想实施来自 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));
}
【问题讨论】:
-
您是否有理由不使用
Contract.Assume?出现次数太多了? -
我们试图远离 Contract.Assume,但是是的,有不少出现,我们会继续添加更多。
-
我猜问题是获取表达式/方法信息的各种方法不
Ensure结果是非空的。您是否考虑过使用一些包装方法,例如:social.msdn.microsoft.com/Forums/en-NZ/codecontracts/thread/… 中给出的那些?这样您只需将Assume放在一个地方,这样您的Assume使用率就会降到最低。 -
这是一个好主意,但问题是合约违反发生在对方法的调用中,而不是 within 方法(因为该方法需要传递一个表达式) .我将添加一个示例。
-
在您的真实代码中,您是否通过表达式树构建
n=>n.Value?您的错误提到了Expression.Property,但示例中没有出现。
标签: c# code-contracts suppressmessage