为什么+运算符在任何null参数时都不会抛出任何异常?

Mir*_*mvs 2 c# string null

对于我的无知感到抱歉,但我已经尝试了很长时间而没有对此进行合理的解释:为什么+操作符在任何参数出现时都不会抛出任何异常null; 例如:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    class Program
    {
        static void Main(string[] args) {

            string str = null;
            Console.WriteLine(str + "test");
            Console.ReadKey();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Son*_*nül 8

因为C#编译器在您的操作中将+运算符转换为String.Concat方法,并且此方法""在您尝试连接时使用空字符串null.

文件 ;

使用空字符串代替任何null参数.

并从7.7.4加法运算符

当一个或两个操作数的类型为字符串时,binary +运算符执行字符串连接.如果字符串连接的操作数是 null,则替换空字符串.否则,通过调用ToString从类型object继承的虚方法,将任何非字符串参数转换为其字符串表示形式.如果ToString 返回null,则替换空字符串.

也来自参考资料 ;

if (IsNullOrEmpty(str0))
{
     if (IsNullOrEmpty(str1))
     {
         return String.Empty;
     }
     return str1;
}
Run Code Online (Sandbox Code Playgroud)