简体   繁体   中英

Can I overload an == operator on an Interface?

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?

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.

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)

除了CodeInChaos的回答,您可能有兴趣阅读重写 Equals() 和 Operator == 的指南

Since introduction of C# 8 you can provide interfaces with default implementations and static methods (which allows you o define operators for interfaces)

More here: https://docs.microsoft.com/dotnet/csharp/tutorials/default-interface-methods-versions

你在这里谈论的是一个实现细节,一个接口不应该(不能)定义它是如何实现的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM