4

我在String.Format()中有一個null的參數之一,所以調用拋出NullReferenceException。爲什麼檢查發生,即使參數不在結果字符串中?在String.Format中的空args拋出NullReferenceException甚至arg不在結果字符串中

class Foo 
{ 
    public Exception Ex { get; set; } 
} 

class Program 
{ 
    public static void Main(string[] args) 
    { 
     var f1 = new Foo() { Ex = new Exception("Whatever") }; 
     var f2 = new Foo();   

     var error1 = String.Format((f1.Ex == null) ? "Eror" : "Error: {0}", f1.Ex.Message); // works 
     var error2 = String.Format((f2.Ex == null) ? "Eror" : "Error: {0}", f2.Ex.Message); // NullReferenceException 
    } 
} 

是否有除由if()分開的兩個電話的任何變通辦法?

回答

8

這是因爲在這兩種情況下你最終都會評估f2.Ex.Message

應該是:

var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message); 
+0

+1打我吧... – 2010-02-18 09:43:09

+0

+1的代碼示例,這也解釋了點比Darins回答更好。 – Mauro 2010-02-18 09:47:12

6

這不是string.Format是拋出異常,但是這個:f2.Ex.Message。您正在撥打Message獲得者Ex屬性爲null。

相關問題