我在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()
分開的兩個電話的任何變通辦法?
+1打我吧... – 2010-02-18 09:43:09
+1的代碼示例,這也解釋了點比Darins回答更好。 – Mauro 2010-02-18 09:47:12