为什么 + 运算符在任何 null 参数时都不会抛出任何异常?
Why + operator doesn't throw any exception when any null parameters?
抱歉我的无知,但我已经尝试了很长时间而没有对此做出合理的解释:
为什么 +
运算符在任何参数为 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();
}
}
}
因为 C# 编译器在您的操作中将 +
运算符转换为 String.Concat
method,并且此方法在您尝试连接 null
.[=26= 时使用空字符串 ""
]
来自 documentation;
An Empty string is used in place of any null
argument.
The binary + operator performs string concatenation when one or both
operands are of type string. If an operand of string concatenation is
null
, an empty string is substituted. Otherwise, any non-string
argument is converted to its string representation by invoking the
virtual ToString
method inherited from type object. If ToString
returns null
, an empty string is substituted.
也来自 reference source;
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return String.Empty;
}
return str1;
}
抱歉我的无知,但我已经尝试了很长时间而没有对此做出合理的解释:
为什么 +
运算符在任何参数为 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();
}
}
}
因为 C# 编译器在您的操作中将 +
运算符转换为 String.Concat
method,并且此方法在您尝试连接 null
.[=26= 时使用空字符串 ""
]
来自 documentation;
An Empty string is used in place of any
null
argument.
The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is
null
, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtualToString
method inherited from type object. IfToString
returnsnull
, an empty string is substituted.
也来自 reference source;
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return String.Empty;
}
return str1;
}