c# How to find if two objects are equal

前端 未结 6 1969
北荒
北荒 2020-12-08 02:40

I want to know the best way to compare two objects and to find out if they\'re equal. I\'m overriding both GethashCode and Equals. So a basic class looks like:



        
6条回答
  •  情歌与酒
    2020-12-08 03:31

    Your Equals is incorrect - that should define what it means for two things to be equal - and having the same hash-code does not mean equality (however; a different hash-code does mean non-equality). If "equality" means "both strings are pairwise equal", then test that.

    Re a better hash; xor is notorious for this, since it is trivial to get 0 by xor a value with itself. A better approach may be something like:

    int i = 0x65407627;
    i = (i * -1521134295) + Value.GetHashCode();
    i = (i * -1521134295) + (String1 == null ? 0 : String1.GetHashCode());
    i = (i * -1521134295) + (String2 == null ? 0 : String2.GetHashCode());
    return i;
    

提交回复
热议问题