问题描述
我有几个地方我需要比较2(可为空)值,看看它们是相同的。
I have a few places where I need to compare 2 (nullable) values, to see if they're the same.
我觉得应该有东西在该框架支持这一点,但无法找到任何东西,这样反而有以下几点:
I think there should be something in the framework to support this, but can't find anything, so instead have the following:
public static bool IsDifferentTo(this bool? x, bool? y)
{
return (x.HasValue != y.HasValue) ? true : x.HasValue && x.Value != y.Value;
}
然后,在代码中,我有如果(X。 IsDifferentTo(Y))...
然后我有可能为空的整数,可为空双打等类似的方法。
I then have similar methods for nullable ints, nullable doubles etc.
有没有一个更简单的方法来查看两个可空类型是相同的。
Is there not an easier way to see if two nullable types are the same?
更新:
事实证明,这种方法存在的原因是因为代码已经从VB.Net,这里没有=无返回false转换(对比C#其中null == NULL返回true )。在VB.Net代码应该用 .Equals ...
代替。
Turns out that the reason this method existed was because the code has been converted from VB.Net, where Nothing = Nothing returns false (compare to C# where null == null returns true). The VB.Net code should have used .Equals...
instead.
推荐答案
C#支持解禁的运营商,因此,如果类型(布尔
在这种情况下?)在编译时知道你应该只能够使用:
C# supports "lifted" operators, so if the type (bool?
in this case) is known at compile you should just be able to use:
return x != y;
如果你需要仿制药,那么 EqualityComparer< T> .DEFAULT
是你的朋友!
If you need generics, then EqualityComparer<T>.Default
is your friend:
return !EqualityComparer<T>.Default.Equals(x,y);
请注意,但是,这两种方法都使用空==空
的方法(对比ANSI SQL)。如果你需要!空= NULL
,那么你就必须测试分别:
Note, however, that both of these approaches use the "null == null
" approach (contrast to ANSI SQL). If you need "null != null
" then you'll have to test that separately:
return x == null || x != y;
这篇关于如何比较可空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!