我可以在接口上重载

我可以在接口上重载

本文介绍了我可以在接口上重载 == 运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的界面:

public interface IFoo
{
  int A {get;}
  int B {get;}
}

而且我有多个实现 IFoo 的类.
我想检查相等性,而不是基于 ReferenceEquality,但是如果 A 和 B 相同,则两个 IFoos 应该被认为是相等的(实际上我正在检查通过 WCF 发送的键值对的集合,这就是为什么我可以'没有 ReferenceEquality).
现在,如果我有:

and I have multiple classes implementing IFoo.
I want to check equality, not based on ReferenceEquality, but two IFoos should be considered equal, if both A and B is the same (in reality I'm checking a collection of Key-Value pairs sent through WCF, that is why I can't have ReferenceEquality).
Now if I have:

IFoo first = new FooBar1() { A = 1, B = 1};
IFoo second = new FooBar2() { A = 1, B = 1};
if (first == second) {
 //this should return true
}

当前 IFooIEquatable,所以 FooBar1 和 FooBar2 覆盖 Equals(IFoo other),但这不是被调用的==.我正在寻找我的代码以在任何地方用 a.Equals(b) 替换 a==b ,但这并不好.

Currently IFoo is IEquatable<IFoo>, so FooBar1 and FooBar2 overrides Equals(IFoo other), but that's not what gets called on ==. I'm hunting through my code to replace a==b with a.Equals(b) everywhere, but that's just not nice.

我能做什么?

推荐答案

不,你不能.重载 == 需要您使用的其中一种类型的静态方法,并且接口不能包含这些方法.扩展方法也无济于事.所以在接口 == 总是使用引用相等.

No, you can't. Overloading == requires static methods in one of the types you use, and an interface can't contain those. Extension methods can't help either. So on interfaces == is always using reference equality.

请注意,如果 a==null,a.Equals(b) 将抛出异常.

Note that a.Equals(b) will throw an exception if a==null.

这篇关于我可以在接口上重载 == 运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 00:33