4

null引数の 1 つにあるのでString.Format()、 throws を呼び出します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 
    }
}

で区切られた 2 つの呼び出し以外の回避策はあります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 のプロパティでMessageゲッターを呼び出しています。Ex

于 2010-02-18T09:39:19.077 に答える