是否可以为接口引用定义==的行为?

时间:2021-01-10 16:21:54

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

如果接口继承IEquatable,则实现类可以定义Equals方法的行为。是否可以定义==操作的行为?

public interface IFoo : IEquatable  
{}  

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

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

通过比较它们的值来检查两个IFoo引用是否相等:

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

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

Is it possible to make if (X == Y) use the Equals method on Foo?

是否可以使if(X == Y)在Foo上使用Equals方法?

2 个解决方案

#1


6  

No - you can't specify operators in interfaces (mostly because operators are static). The compiler determines which overload of == to call based purely on their static type (i.e. polymorphism isn't involved) and interfaces can't specify the code to say "return the result of calling X.Equals(Y)".

否 - 您无法在接口中指定运算符(主要是因为运算符是静态的)。编译器确定哪个==的重载完全基于它们的静态类型进行调用(即不涉及多态),并且接口不能指定代码来说“返回调用X.Equals(Y)的结果”。

#2


0  

No, because interface can't contain operator functions. A solution would be to make IFoo an abstract class instead of an interface :

不,因为接口不能包含操作员功能。一个解决方案是使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
    }
}

Of course, this makes you lose the flexibility provided by interfaces.

当然,这会让您失去接口提供的灵活性。

#1


6  

No - you can't specify operators in interfaces (mostly because operators are static). The compiler determines which overload of == to call based purely on their static type (i.e. polymorphism isn't involved) and interfaces can't specify the code to say "return the result of calling X.Equals(Y)".

否 - 您无法在接口中指定运算符(主要是因为运算符是静态的)。编译器确定哪个==的重载完全基于它们的静态类型进行调用(即不涉及多态),并且接口不能指定代码来说“返回调用X.Equals(Y)的结果”。

#2


0  

No, because interface can't contain operator functions. A solution would be to make IFoo an abstract class instead of an interface :

不,因为接口不能包含操作员功能。一个解决方案是使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
    }
}

Of course, this makes you lose the flexibility provided by interfaces.

当然,这会让您失去接口提供的灵活性。