盒装的比较值类型 [英] Comparing boxed value types
问题描述
今天,我偶然发现了一个有趣的错误,我写。我有一组可通过一般的setter方法来设置属性。这些特性可以是值类型或引用类型。
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 types.
public void SetValue( TEnum property, object value )
{
if ( _properties[ property ] != value )
{
// Only come here when the new value is different.
}
}
在写这个方法,我发现了一个单元测试条件始终是值类型如此。它没有多久我要弄清楚这是由于装箱/拆箱。它没有多久我要么调整代码如下:
When writing a unit test for this method I found out the condition is always true for value types. It didn't take me long to figure out this is due to boxing/unboxing. It didn't take me long either to adjust the code to the following:
public void SetValue( TEnum property, object value )
{
if ( !_properties[ property ].Equals( value ) )
{
// Only come here when the new value is different.
}
}
的事情是我不能完全满足于此解。我想保持一个简单的参考比较,除非该值是盒装。
The thing is I'm not entirely satisfied with this solution. I'd like to keep a simple reference comparison, unless the value is boxed.
目前的解决方案我想到的只是调用等于( )
的盒装值。做的盒装检查值似乎有点矫枉过正。难道没有更简单的方法?
The current solution I am thinking of is only calling Equals()
for boxed values. Doing a check for a boxed values seems a bit overkill. Isn't there an easier way?
推荐答案
如果你需要,当你处理一个值类型,那么你不同的行为再显然将需要进行某种形式的测试。你并不需要的盒装的值类型明确的检查,因为所有的值类型将被装箱**由于参数被类型为对象$ C $ 。C>
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.
}
}
(**是的,我知道可空< T>
是一个值类型有自己的特殊规则有关装箱和拆箱,但是这几乎是无关紧要这里)
( ** And, yes, I know that Nullable<T>
is a value-type with its own special rules relating to boxing and unboxing, but that's pretty much irrelevant here.)
这篇关于盒装的比较值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!