Expression> 类型的嵌套类型的替代方案
我有一个调用服务时使用的函数。在调用服务之前,它将创建一个日志条目:
protected TResult CallService<TService, TResult>(TService service,
Expression<Func<TService, TResult>> functionSelector)
{
Logger.LogServiceCall(service, functionSelector);
return functionSelector.Compile()(service);
}
Visual Studio 2010 代码分析器在以下消息中通知我不应使用嵌套类型:
CA1006:Microsoft.Design:考虑 设计在哪里 'ServiceManager.CallService
(TService, 表达式 >)' 不嵌套泛型类型 '表达式 >'。
虽然我可以简单地为此条目创建抑制规则,但是否存在替代方案可以防止显示此类警告?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在这种情况下我会抑制它,因为调用者不必处理嵌套泛型,他只是传递一个 lambda 表达式,这很容易使用。
CA 不会对 lambda 表达式设置例外。有时抑制它比编写奇怪的代码更好。
I would suppress it in this case, with the reason that the caller doesn't have to cope with nested generics, he is just passing a lambda expression, which is easy to use.
CA does not make exceptions for lambda expressions. Sometimes It is better to suppress it then to write weird code.
老实说,大多数时候我都会禁止该规则。虽然我可以理解某些嵌套类型的构造是可以避免的,但情况往往并非如此;您通常希望将其留给调用站点,因为您无法保证调用站点将希望以相同的方式实例化嵌套泛型类型。
这是我觉得有点专横的规则之一;我基本上同意其中的大多数,但不同意这一点。
I'll be honest, I suppress that rule most of the time. While I can understand that some of the construction of the nested types can be avoided, it is more often than not the case; you usually want to leave that to the call site because you can't guarantee that the call site will want the nested generic type to be instantiated in the same way.
This is one of those rules that I find a bit overbearing; I generally agree with most of them, but not this one.
像您这样的方法在 Linq 中广泛使用,例如:
另一种方法是声明委托类型来替换嵌套的 Func,但这同样可能会让更有经验的开发人员感到困惑谁习惯于使用表达式树。
微软显然对嵌套泛型表达式类型的 CA1006 做出了例外,我们也应该如此。
Methods like yours are used extensively in Linq, for example:
The alternative would be to declare a delegate type to replace the nested
Func<TService, TResult>
, but that's just as likely to confuse a more experienced developer who's used to working with expression trees.Microsoft obviously makes an exception to CA1006 for nested generic expression types, and so should we.
您可以使用 SuppressMessageAttribute 抑制消息警告。
You can suppress the message warning with SuppressMessageAttribute.