C# 如何比较可空类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2341660/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:36:28  来源:igfitidea点击:

How to compare nullable types?

c#extension-methodsnullable

提问by David_001

I have a few places where I need to compare 2 (nullable) values, to see if they're the same.

我有几个地方需要比较 2 个(可为空的)值,以查看它们是否相同。

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;
}

Then, within code I have if (x.IsDifferentTo(y)) ...

然后,在代码中我有 if (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?

没有更简单的方法来查看两个可空类型是否相同?

Update:

更新:

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.

原来这个方法存在的原因是因为代码是从 VB.Net 转换而来的,其中 Nothing = Nothing 返回 false(与 C# 相比,null == null 返回 true)。应该使用 VB.Net 代码.Equals...

采纳答案by Marc Gravell

C# supports "lifted" operators, so if the type (bool?in this case) is known at compile you should just be able to use:

C# 支持“提升”运算符,因此如果类型(bool?在本例中)在编译时已知,您应该能够使用:

return x != y;

If you need generics, then EqualityComparer<T>.Defaultis your friend:

如果您需要泛型,那么EqualityComparer<T>.Default您的朋友是:

return !EqualityComparer<T>.Default.Equals(x,y);

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:

但是请注意,这两种方法都使用“ null == null”方法(与 ANSI SQL 相对)。如果您需要“ null != null”,那么您必须单独测试:

return x == null || x != y;

回答by Mark Seemann

You can use the static Equalsmethod on System.Object:

您可以在 System.Object 上使用静态Equals方法:

var equal = object.Equals(objA, objB);

回答by Anton Gogolev

回答by Lucero

Just use ==, or .Equals().

只需使用==, 或.Equals()

回答by Kashif

if (x.Equals(y)) 

回答by hdd42

I wanted to find how to compare two nullable int on C#, but I always get this link after search, so if someone needs to compare exactly two nullable int, then this can be helpful

我想找到如何在 C# 上比较两个可为空的 int,但我总是在搜索后得到这个链接,所以如果有人需要比较两个可为空的 int,那么这可能会有所帮助

a.GetValueOrDefault(int.MinValue).CompareTo(b.GetValueOrDefault(long.MinValue));

a.GetValueOrDefault(int.MinValue).CompareTo(b.GetValueOrDefault(long.MinValue));