我在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