Comparing boxed value types

后端 未结 5 1041
轮回少年
轮回少年 2020-11-28 13:06

Today I stumbled upon an interesting bug I wrote. I have a set of properties which can be set through a general setter. These properties can be value types or reference type

5条回答
  •  伪装坚强ぢ
    2020-11-28 14:00

    How about this:

    if(object.ReferenceEquals(first, second)) { return; }
    if(first.Equals(second)) { return; }
    
    // they must differ, right?
    

    Update

    I realized this doesn't work as expected for a certain case:

    • For value types, ReferenceEquals returns false so we fall back to Equals, which behaves as expected.
    • For reference types where ReferenceEquals returns true, we consider them "same" as expected.
    • For reference types where ReferenceEquals returns false and Equals returns false, we consider them "different" as expected.
    • For reference types where ReferenceEquals returns false and Equals returns true, we consider them "same" even though we want "different"

    So the lesson is "don't get clever"

提交回复
热议问题