C# 字符串中为Null。格式参数抛出NullReferenceException,即使参数为';动结式字符串中的t
我在C# 字符串中为Null。格式参数抛出NullReferenceException,即使参数为';动结式字符串中的t,c#,.net,exception-handling,string-formatting,nullreferenceexception,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("
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()
分隔的两个调用之外,还有其他解决方法吗?引发异常的不是string.Format
,而是:f2.Ex.Message
。您正在调用Ex
属性上的Message
getter,该属性为null。这是因为您将在两种情况下都要计算f2.Ex.Message
应该是:
var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message);
+1对于代码示例,它比Darins的答案更好地解释了这一点。