String.Format args中的Null抛出NullReferenceException,即使arg不在结果字符串中

aba*_*hev 4 .net c# exception-handling string-formatting nullreferenceexception

我有一个null参数中的一个参数String.Format()调用抛出NullReferenceException.为什么即使参数不在结果字符串中也要进行检查?

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 
    }
}
Run Code Online (Sandbox Code Playgroud)

除了两个被分隔的呼叫之外,还有其他解决方法if()吗?

Pao*_*olo 8

这是因为f2.Ex.Message在任何一种情况下你最终都要进行评估.

应该:

var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message);
Run Code Online (Sandbox Code Playgroud)


Dar*_*rov 6

这不是string.Format抛出异常,而是:f2.Ex.Message.您正在调用属性的Messagegetter Ex为null.