为什么添加两个空字符串的结果不为空? [英] Why is the result of adding two null strings not null?

查看:44
本文介绍了为什么添加两个空字符串的结果不为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was fiddling around in C# when I came across this weird behavior in .Net programming.

我已编写此代码:

  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 字符串?

I got the output as No meow, which means the string is not null. How is this possible? Why does adding two null strings, result in a non-null string?

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

On debugging when I check the value of xyz after adding it to itself, its value is "" (no characters).

推荐答案

来自 MSDN :

在字符串连接操作中,C#编译器将空字符串与空字符串相同,

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

即使 xyz 为null,也会调用+ =运算符(该运算符会转换为对+运算符(*))不会抛出 NullReferenceException ,因为它是 static 方法.用伪代码:

Even though xyz is null, calling the += operator (which is converted to a call to the + operator (*)) on it does not throw a NullReferenceException because it's a static method. In pseudo code:

xyz = String.+(null, null);

然后实现将其解释为原样

The implementation will then interpret this as if it was

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


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


(*) Section §7.17.2 of the C# specification:

x op = y 形式的操作通过应用二进制运算符重载分辨率(第7.3.4节)来处理,就好像该操作写为 x op y 一样.

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.

这篇关于为什么添加两个空字符串的结果不为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆