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。

相关问题