2015-01-16 63 views
2

對不起,我的無知,但我一直試圖很長一段時間沒有一個合理的解釋: 爲什麼+運算符不會拋出任何異常時,任何參數是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(); 
     } 
    } 
} 
+1

因爲'string.Concat(...)'允許'null'參數 – leppie

回答

8

因爲C#編譯器將+運營商在你的操作String.Concat method這種方法使用空字符串""當您嘗試來連接null

documentation;

使用空字符串代替任何null參數。

而且從7.7.4 Addition operator

二進制+運算符執行字符串連接時一個或兩個 操作數是字符串類型。如果字符串連接的操作數是 null,則會替換空字符串。否則,通過調用從對象類型繼承的 虛擬ToString方法,將任何非字符串 參數轉換爲其字符串表示形式。如果ToString 返回null,則替換空字符串。

也來自reference source;

if (IsNullOrEmpty(str0)) 
{ 
    if (IsNullOrEmpty(str1)) 
    { 
     return String.Empty; 
    } 
    return str1; 
} 
相關問題