开发者

Whats the cleanest/best way to implement Equals and GetHashCode on 3rd party types you don't have access to?

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 t开发者_运维百科o 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; }
}


If you need to use ClassA as a dictionary key, you can implement your own class that implement IEqualityComparer<ClassA>, and pass it to the constructor of the dictionary. This allows you to override the type's GetHashCode and Equals methods.


I would inherit from ClassA and override Equals and GetHashCode.

You will need to base your implementation on the public properties, since there is no way you have access to the private fields.


Inherit your own class from ClassA and then implement GetHashCode and Equals in it.


As per Griver and Driis above - inherit or aggregate ClassA and implement Equals based on the a properties.

MSDN publishes some guidelines here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜