Can I overload an == operator on an Interface?

后端 未结 4 827

I have an interface like this:

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

and I have multiple classes implementing IFoo.
I

相关标签:
4条回答
  • 2020-12-07 01:12

    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)

    0 讨论(0)
  • 2020-12-07 01:13

    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.

    0 讨论(0)
  • 2020-12-07 01:13

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

    0 讨论(0)
  • 2020-12-07 01:17

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

    0 讨论(0)
提交回复
热议问题