NET问答: 为什么 null + true = string 呢?

咨询区

Javed Akram

请问 null + true 为什么是一个 string 类型的 True,代码如下:.

        static void Main(string[] args)
        {
            string b = null + true;

            Console.WriteLine(b);
        }

NET问答: 为什么 null + true = string 呢?

谁知道这背后的原理?

回答区

JaredPar

这是因为你一旦引入了 + ,C# 操作符绑定规则就起作用了,编译器会帮你选择 + 的最佳重载方法,比如下面这个:

string operator +(string x, object y)

显而易见,上面的 操作符重载 刚好就能容纳你的 null + true,如果把代码再补全一下就是 ((string)null) + true ,所以最后结果就是 True

顺便提一下,C# 语言规格书的第 7.7.4 节就聊到了这个决议。

点评区

其实这种问题挺无聊的,现实开发中应该没人会这么写吧,真有的话,要么是炫技,要么是 StringBuilder 的简写,我就简单聊聊吧,主要有两点。

  • 真的是 operator 吗?

我翻遍了所有源码都没有找到所谓的 string operator +(string x, object y) ,最后不经意间在 VS 的快捷提示中找到了。。。

NET问答: 为什么 null + true = string 呢?

真是强大的 VisualStudio,很显然这是一个语法糖。

  • 反编译 DLL 看底层实现逻辑

先说一下程序写在 .NETCore 3.1 上,我用 ILSpy 反编译一下,如下图:

NET问答: 为什么 null + true = string 呢?

看到没有? 编译器已经帮你转了一个更加简单粗暴的写法:string b = true.ToString() ?? ""; 这代码意图是不是更明显 ?

什么,你说我 ILSpy 有问题,居然没调用 String.Concat ?好吧,那我用 DnSpy 反编译看看。。。

NET问答: 为什么 null + true = string 呢?

没错,就是一样的写法,连 String.Concat 都省了,牛逼。