比较“”与String.Empty和Null Coalesce运算符(??)的混淆行为

时间:2017-06-23 18:11:19

标签: c# string null-coalescing-operator

enter image description here

这里显示的行为对我来说非常困惑。如果""等于String.Empty,并且空合并(??)适用于"" ?? "It works",那么为什么test ?? "It works"String.Empty ?? "It works"不会相应地采取行动?

注意: Console.WriteLine("It works",String.Empty ?? "It works");会抛出完全相同的AssertFailedException

** 更新#1 **

目前的答案与结果不符。如这些例子所示......

  • "" == String.Emptytrue
  • null == ""true
  • null == String.Emptyfalse

这些彼此不一致。这是A = B,B = C的情况,但A!= C

enter image description here

** 更新#2 **

回答@Willem Van Onsem关于使用Console.WriteLine("" == null);

的问题

enter image description here enter image description here

这将是预期的结果。因此,似乎这可能是Assert.AreEqual(...,...)

特有的问题

** 更新#3 **

请注意,我完全了解并且在发布此问题之前,??的工作原理以及"" == nullfalse的方式。我知道它只应检查null的相等性。我知道x ?? y相当于x != null ? x : y。这在答案和评论中已经完全重复了,以至于它变得侮辱了。考虑一下,如果我不知道运算符假设如何工作并且想到第一个Assert之后的任何事情应该通过,那么为什么我会感到困惑并发布问题?

3 个答案:

答案 0 :(得分:4)

null-coalescing operator ??检查nullx ?? y简称:

x == null ? y : x

因此,如果您有一个空字符串,那么x == null会失败(意味着它是false),因此"" ?? "It works"会导致"",我们可以看到csharp交互式shell:

csharp> "" ?? "It works"
""
csharp> "" == null
false

或者如文档中所述:

  

??运算符称为null-coalescing运算符。如果操作数不是null ,则返回左侧操作数;否则它会返回右手操作数。

编辑:关于更新#1:

当我在csharp交互式shell上运行查询时(这是 Mono C#shell ):

csharp> "" == String.Empty
true                                    
csharp> null == ""                      
false                                   
csharp> null == String.Empty            
false

似乎搞砸了IDE。

答案 1 :(得分:3)

Null coalesce运算符理解null,但不知道空字符串,这显然与null不同。

如果您想以相同的方式处理空字符串和null,请使用string.IsNullOrEmpty

Assert.AreEqual("It works", !String.IsNullOrEmpty(test) ? test : "It works")

答案 2 :(得分:0)

我打算走出困境并说有一个IDE错误,其中Debug Exception警告框指向错误的行。这些事情发生了。 Stacktraces可以说谎,代码可以最终优化,以便排序不同。谁知道。为了验证:

var test = String.Empty;

Assert.AreEqual("", String.Empty);
Assert.AreEqual("Case 1", "" ?? "Case 1");
Assert.AreEqual("Case 2", test ?? "Case 2");
Assert.AreEqual("Case 3", String.Empty ?? "Case 3");

以下是向Microsoft报告此问题的链接,其中包含第二人的确认和显示其发生的视频: https://connect.microsoft.com/VisualStudio/feedback/details/641947/exception-assistant-highlights-incorrect-line-of-code