FxCop 和 IComparable/IComparable

发布于 2024-07-22 07:45:32 字数 412 浏览 6 评论 0原文

我目前正在调查 FxCop 在我们现有项目之一中的使用,并得到了一个奇怪的结果。

输出显示少量违反“重写可比较类型上的方法”规则,指出“‘Log’应该重写 Equals,因为它实现了 IComparable”。

这有两个问题:

  1. 我认为在实现IComparable时只需要实现CompareTo(MSDN本身也证实了这一点)
  2. 该类没有实现IComparable< /code> 但 IComparable 并且将 CompareTo 实现为强类型。

所以 FxCop (1.36) 抛出了一个不稳定的问题,还是我的理解不正常……?

提前致谢。

I'm currently investigating the use of FxCop with one of our existing projects and am getting an odd result.

The output displays a small number of breaches of the 'Override methods on comparable types' rule stating "'Log' should override Equals since it implements IComparable."

There are two issues with this:

  1. I thought that it was only necessary to implement CompareTo when implementing IComparable (MSDN itself confirms this)
  2. The class is not implementing IComparable but IComparable<T> and does impliment CompareTo as strongly typed.

So it FxCop (1.36) throwing a wobbly or is it my understanding thats out of whack here..?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

隱形的亼 2024-07-29 07:45:32

FxCop 是一个相当偏执的工具......在这种情况下,我想,它试图警告您,您正在以某种方式更改比较逻辑,并且您不应该忘记在需要时更改相等逻辑。 你看,CompareTo方法有时会返回0,这应该与使用Equals一致。

如果这不是您的情况,并且您确定不需要任何重载(MSDN 中的示例表明您还需要覆盖所有其他相等运算符)...然后只需抑制警告或禁用它即可。

FxCop is a quite paranoidal tool... In this case, I suppose, it is trying to warn you, that you are changing the logic of comparison somehow and you shouldn't forget changing the equality logic if needed. You see, CompareTo method sometimes returns 0, which should be consistent with using Equals.

If this is not really your case, and you are sure you don't need any of the overloading (an example in MSDN shows that you will need to override all other equalty operators as well)... then just supress the warning or disable it.

七七 2024-07-29 07:45:32

我会重写 Equals,

  • 只需在您的方法中调用 base.Equals
  • 并添加一条注释来解释为什么上述内容就是所需要的。

这样 FxCop 会很高兴,下一个查看您的代码的程序员也会很高兴。 (在极少数情况下,由于原貌问题,您无法执行上述操作,但现在这种情况很少见。

I would override Equals,

  • just call base.Equals in your method
  • and add a comment explaining why the above is all that is needed

That way FxCop is happy, and so is the next programmer that looks at your code. (In a very few cases you can't do the above due to proforance problems, but these are rare these days.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文