How do I assert equality on two classes without an equals method?

后端 未结 23 1670
臣服心动
臣服心动 2020-11-28 05:20

Say I have a class with no equals() method, to which do not have the source. I want to assert equality on two instances of that class.

I can do multiple asserts:

23条回答
  •  误落风尘
    2020-11-28 06:07

    This won't help the OP, but it might help any C# developers who end up here...

    Like Enrique posted, you should override the equals method.

    Is there a better practice to get what I want from the object, without subclassing and overridding equals (ugh)?

    My suggestion is to not use a subclass. Use a partial class.

    Partial Class Definitions (MSDN)

    So your class would look like...

    public partial class TheClass
    {
        public override bool Equals(Object obj)
        {
            // your implementation here
        }
    }
    

    For Java, I would agree with the suggestion to use reflection. Just remember that you should avoid using reflection whenever possible. It is slow, hard to debug, and even harder to maintain into the future because IDEs could break your code by doing a field rename or something like that. Be careful!

提交回复
热议问题