4

我在所谓的 throwsnull中有一个论点。为什么即使参数不在结果字符串中也会进行检查?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 
    }
}

除了用 分隔的两个调用外,还有其他解决方法if()吗?

4

2 回答 2

8

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

应该:

var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message);
于 2010-02-18T09:40:11.607 回答
6

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

于 2010-02-18T09:39:19.077 回答