可以为接口引用定义 == 的行为吗?
如果接口继承 IEquatable,则实现类可以定义 Equals 方法的行为。 是否可以定义 == 操作的行为?
public interface IFoo : IEquatable
{}
public class Foo : IFoo
{
// IEquatable.Equals
public bool Equals(IFoo other)
{
// Compare by value here...
}
}
通过比较两个 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 an interface inherits IEquatable the implementing class can define the behavior of the Equals method. Is it possible to define the behavior of == operations?
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不 - 您不能在接口中指定运算符(主要是因为运算符是静态的)。 编译器纯粹根据其静态类型(即不涉及多态性)来确定要调用 == 的哪个重载,并且接口不能指定代码来表示“返回调用 X.Equals(Y) 的结果”。
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)".
不可以,因为接口不能包含运算符函数。 一个解决方案是使 IFoo 成为一个抽象类而不是接口:
当然,这会使您失去接口提供的灵活性。
No, because interface can't contain operator functions. A solution would be to make IFoo an abstract class instead of an interface :
Of course, this makes you lose the flexibility provided by interfaces.