我有这个例程:
try
{
CurrentSessionName = SelectedSession?.Name ?? "No Session Selected";
CurrentSessionTolerance = SelectedSession?.Tolerance.ToString() ?? "N/A";
CurrentSessionVerification = SelectedSession?.Verification.Description ?? "N/A";
}
catch (Exception ex)
{
var whatever = ex.GetType(); // hits here with no provided information
Console.WriteLine("Null Reference Exception"); // ignores this
string name = SelectedSession?.Name; // and this
}
那么,即使NullReferenceException
不是空的,为什么它仍会抛出SelectedSession
错误?
答案 0 :(得分:5)
空传播算子很棒 - 但它并没有神奇地消除空值。
此代码段
SelectedSession?.Tolerance
如果SelectedSession
为空,则不会出错,但会传播,以便上述结果为空。如果SelectedSession
不为null,但Tolerence
为空,则同样适用。
问题是您尝试在空
上调用ToString()
SelectedSession?.Tolerance.ToString()
答案 1 :(得分:3)
Tolerance
或Verification
可以为null,并且您在空指针上调用ToString()
函数。
您无法在空指针上调用ToString()
。