在您无权访问的第 3 方类型上实现 Equals 和 GetHashCode 的最干净/最佳方法是什么?
问题是你有一个第三方类型,例如下面的 ClassA。我无权访问该代码,并且它没有实现 Equals 和 GetHashCode,因此我认为我需要编写一个包装器类。 Equals 和 GetHashCode 实现应使用所有私有成员字段。
最好的方法是什么?我应该使用快捷方式或模式吗?
谢谢
public class ClassA
{
public int FieldA {get; set;}
public double FieldB { get; set; }
public string FieldC { get; set; }
}
The problem is you have a 3rd party type e.g. ClassA below. I don't have access to the code and it doesn't implement Equals and GetHashCode therefore I need to write a wrapper class I think. The Equals and GetHashCode impls should use all the private member fields.
What's the best way to do this? Is there a shortcut or pattern I should be using?
Thanks
public class ClassA
{
public int FieldA {get; set;}
public double FieldB { get; set; }
public string FieldC { get; set; }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您需要使用
ClassA
作为字典键,您可以实现自己的实现IEqualityComparer
的类,并将其传递给字典的构造函数。这允许您重写类型的GetHashCode
和Equals
方法。If you need to use
ClassA
as a dictionary key, you can implement your own class that implementIEqualityComparer<ClassA>
, and pass it to the constructor of the dictionary. This allows you to override the type'sGetHashCode
andEquals
methods.我将从 ClassA 继承并覆盖
Equals
和GetHashCode
。您需要将实现基于公共属性,因为您无法访问私有字段。
I would inherit from ClassA and override
Equals
andGetHashCode
.You will need to base your implementation on the public properties, since there is no way you have access to the private fields.
从ClassA继承自己的类,然后在其中实现GetHashCode和Equals。
Inherit your own class from ClassA and then implement GetHashCode and Equals in it.
根据上面的 Griver 和 Driis - 继承或聚合 ClassA 并基于 a 属性实现 Equals。
MSDN 在此处发布了一些指南
As per Griver and Driis above - inherit or aggregate ClassA and implement Equals based on the a properties.
MSDN publishes some guidelines here