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()吗?
这是因为f2.Ex.Message在任何一种情况下你最终都要进行评估.
应该:
var error2 = (f2.Ex == null) ? "Eror" : String.Format("Error: {0}", f2.Ex.Message);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2357 次 |
| 最近记录: |