Comparing boxed value types

后端 未结 5 1028
轮回少年
轮回少年 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 13:42

    If you need different behaviour when you're dealing with a value-type then you're obviously going to need to perform some kind of test. You don't need an explicit check for boxed value-types, since all value-types will be boxed** due to the parameter being typed as object.

    This code should meet your stated criteria: If value is a (boxed) value-type then call the polymorphic Equals method, otherwise use == to test for reference equality.

    public void SetValue(TEnum property, object value)
    {
        bool equal = ((value != null) && value.GetType().IsValueType)
                         ? value.Equals(_properties[property])
                         : (value == _properties[property]);
    
        if (!equal)
        {
            // Only come here when the new value is different.
        }
    }
    

    ( ** And, yes, I know that Nullable is a value-type with its own special rules relating to boxing and unboxing, but that's pretty much irrelevant here.)

提交回复
热议问题