Is it possible to define the behavior for == to refer to an interface?

If the interface inherits IEquatable, the implementing class can determine the behavior of the Equals method. Is it possible to determine the behavior of == operations?

public interface IFoo : IEquatable  
{}  

public class Foo : IFoo  
{  
    // IEquatable.Equals  
    public bool Equals(IFoo other)  
    {  
        // Compare by value here...
    }  
}

To verify that two IFoo references are equal by comparing their values:

IFoo X = new Foo();  
IFoo Y = new Foo();

if (X.Equals(Y))  
{  
     // Do something  
}

Can I use if (X == Y)the Equals method on Foo?

+3
source share
2 answers

No - you cannot specify statements in interfaces (mainly because statements are static). The compiler determines which overload == for the call is based solely on their static type (ie, Polymorphism is not involved), and the interfaces cannot specify the code to say "return the result of the call to X.Equals (Y)".

+6
source

, . IFoo :

abstract class IFoo : IEquatable<IFoo> 
{
    public static bool operator ==(IFoo i1, IFoo i2) { return i1.Equals(i2); }
    public static bool operator !=(IFoo i1, IFoo i2) { return !i1.Equals(i2); }
    public abstract bool Equals(IFoo other);
}

class Foo : IFoo
{
    public override bool Equals(IFoo other)
    {
        // Compare
    }
}

, , .

0

Source: https://habr.com/ru/post/1699104/


All Articles