简体   繁体   English

在第三方库中将类的相等函数放在何处?

[英]Where to put the equality function for a class in a third party library?

I'm using a third party library containing a class which lacks both operator==() and Equals(). 我正在使用第三方库,其中包含缺少operator ==()和Equals()的类。 I'd like to implement one myself, but I'm not sure how to name it and where to put it. 我想自己实现一个,但我不确定如何命名以及放在哪里。 I've tried to add both operators as an extension method, but both failed. 我试图将两个运算符添加为扩展方法,但都失败了。 I've now written an IsEqualTo() function, but it results in rather confusing client code. 我现在写了一个IsEqualTo()函数,但它导致相当混乱的客户端代码。 Does anyone know a more elegant solution? 有谁知道更优雅的解决方案?

是继承或包装第三方课程的选择吗?

You won't be able to overload the == operator, but you could create an IEqualityComparer<T> which can be used for dictionaries etc. 您将无法重载==运算符,但您可以创建可用于字典等的IEqualityComparer<T>

While you can write an Equals extension method, it would never be used because the virtual method on Object will always be applicable, and if there's an applicable instance method the compiler doesn't look for extension methods even if there's a more specific one. 虽然您可以编写Equals扩展方法,但它永远不会被使用,因为Object上的虚方法总是适用,如果有适用的实例方法,编译器即使有更具体的方法也不会查找扩展方法。

You might want to rename your IsEqualTo method as ValueEquals or something similar... but I agree it's still not ideal. 您可能希望将IsEqualTo方法重命名为ValueEquals或类似的东西......但我同意它仍然不理想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM