本文介绍了我可以重载在接口上==操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的接口:

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

和我有多个类实现IFoo的。照片我要检查的平等,而不是基于ReferenceEquality,而是两个IFoos应被视为平等的,如果A和B都相同(在现实中我检查通过WCF发送键 - 值对的集合,这就是为什么我可以'T有ReferenceEquality)。
现在,如果我有:

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
}

目前的IFoo IEquatable<的IFoo> ,所以FooBar1和FooBar2覆盖等于( IFoo的除外),但是这不是被调用的==。我通过我的code狩猎替换 A == b a.Equals(B)无处不在,但是这只是不是很好。

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.

我该怎么办?

推荐答案

没有,你不能。重载 == 需要静态方法,您使用的类型之一,并且接口不能包含这些。扩展方法不能帮助的。所以在接口==始终使用引用相等。

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.

注意 a.Equals(B)将抛出一个异常,如果一个== NULL。

Note that a.Equals(b) will throw an exception if a==null.

这篇关于我可以重载在接口上==操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 02:27