c# - Null in String.Format args 抛出 NullReferenceException 即使 arg 不在结果字符串中

标签 c# .net exception-handling string-formatting nullreferenceexception

我在 String.Format() 的参数之一中有一个 null,所以调用抛出 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() 分隔的两个调用之外,是否有任何解决方法?

最佳答案

这是因为无论哪种情况,您最终都会计算 f2.Ex.Message

应该是:

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

关于c# - Null in String.Format args 抛出 NullReferenceException 即使 arg 不在结果字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2287553/

相关文章:

android - 如何捕获未处理的错误并进一步传递它们

c# - 在 HTTP CONNECT over SSL 期间设置用户代理 header ?

.net - 什么是 .NET 框架?

c# - 在 pictureBox 上更改光标

c# - javascript 在 mozilla 中不起作用,但在其他浏览器中起作用

c# - 在不激活的情况下与表单交互

exception - F#异常处理构造

python - 如何从 Celery worker 捕获自定义异常,或阻止它以 `celery.backends.base` 为前缀?

c# - Entity Framework 一对一关系?

c# - BSTR (COM) 的长度