c# - 为什么两个空字符串相加的结果不为空?

标签 c# string null

<分区>

当我在 .Net 编程中遇到这种奇怪的行为时,我正在用 C# 摆弄。

我写了这段代码:

  static void Main(string[] args)
    {
        string xyz = null;
        xyz += xyz;
        TestNullFunc(xyz);
        Console.WriteLine(xyz);

        Console.Read();

    }

    static void TestNullFunc(string abc)
    {
        if (abc == null)
        {
            Console.WriteLine("meow THERE ! ");
        }
        else
        {
            Console.WriteLine("No Meow ");
        }
    }

我得到的输出是No meow,这意味着字符串不是null。这怎么可能?为什么添加两个 null 字符串会导致非 null 字符串?

在调试时,当我在将 xyz 添加到自身后检查它的值时,它的值为 ""(无字符)。

最佳答案

来自 MSDN :

In string concatenation operations, the C# compiler treats a null string the same as an empty string,

即使 xyz 为 null,对其调用 += 运算符(转换为对 + operator (*) 的调用)也不会抛出 NullReferenceException 因为它是一个静态 方法。在伪代码中:

xyz = String.+(null, null);

然后实现会将其解释为好像是

xyz = String.+("", "");

(*) C# 规范的第 7.17.2 节:

An operation of the form x op= y is processed by applying binary operator overload resolution (§7.3.4) as if the operation was written x op y.

关于c# - 为什么两个空字符串相加的结果不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21778406/

相关文章:

c# - $ - 字符串插值实时编译 - 从文件

c# - 如何在 Linq 中实现嵌套 for 循环?

python - 如何在子字符串后捕获一定数量的字符?

c - 对指向字符串文字的指针的算术运算。

string - 为什么我应该使用 SendStr(通过 &str 或 String)作为 Rust 中 Error 结构的消息属性?

objective-c - 什么最能描述零?那到底是什么?

c# - 如何查看一个类型是否实现了一个接口(interface)?

java - null 值被视为对象或数组

sql - MySQL 中的 OR 非空约束

c# - 通用 Windows 窗体模板