我可以在接口上重载 == 运算符吗?
我有一个这样的接口:
public interface IFoo
{
int A {get;}
int B {get;}
}
并且我有多个实现 IFoo 的类。
我想检查相等性,而不是基于 ReferenceEquality,但是如果 A 和 B 相同,则两个 IFoo 应该被视为相等(实际上我正在检查通过 WCF 发送的键值对的集合,这就是为什么我可以没有ReferenceEquality)。
现在,如果我有:
IFoo first = new FooBar1() { A = 1, B = 1};
IFoo second = new FooBar2() { A = 1, B = 1};
if (first == second) {
//this should return true
}
当前 IFoo
是 IEquatable
,因此 FooBar1 和 FooBar2 覆盖 Equals(IFoo other)
,但这不是得到的呼吁==。我正在寻找我的代码,以将 a==b
替换为 a.Equals(b)
,但这不太好。
我能做些什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不,你不能。重载
==
需要您使用的类型之一中的静态方法,而接口不能包含这些方法。扩展方法也无济于事。所以在接口上 == 总是使用引用相等。请注意,如果 a==null,
a.Equals(b)
将抛出异常。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.不,您既不能重载接口上的运算符,也不能确保任何实现者都这样做(因为运算符重载在 C# 中是静态的)
)。
最好的选择就是您所做的,使
IFoo
继承IEquatable
并使用Equals(IFoo)
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 fromIEquatable<IFoo>
and useEquals(IFoo)
除了 CodeInChaos' 答案您可能会感兴趣阅读重写 Equals() 和运算符的指南 ==。
Besides CodeInChaos' answer you may be interested in reading Guidelines for Overriding Equals() and Operator ==.
自引入 C# 8 以来,您可以提供具有默认实现和静态方法的接口(这允许您为接口定义运算符)
更多内容:
https://learn.microsoft.com/dotnet/csharp/教程/默认接口方法版本
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://learn.microsoft.com/dotnet/csharp/tutorials/default-interface-methods-versions
您在这里谈论的是实现细节,接口不应该(不能)定义它是如何实现的。
What you're talking about here is an implementation detail, a Interface should not (cannot) define how it is implemented.