Can I overload an == operator on an Interface?

2019-01-15 18:13发布

I have an interface like this:

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

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
}

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.

What can I do?

4条回答
何必那么认真
2楼-- · 2019-01-15 18:22

No, you can neither overload an operator on an interface, nor ensure that any implementors do so (as operator overloading is static in C# ).

Your best option is what you've done, to make IFoo inherit from IEquatable<IFoo> and use Equals(IFoo)

查看更多
劳资没心,怎么记你
3楼-- · 2019-01-15 18:25

What you're talking about here is an implementation detail, a Interface should not (cannot) define how it is implemented.

查看更多
神经病院院长
4楼-- · 2019-01-15 18:38

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.

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

查看更多
放我归山
5楼-- · 2019-01-15 18:44

Besides CodeInChaos' answer you may be interested in reading Guidelines for Overriding Equals() and Operator ==.

查看更多
登录 后发表回答