为什么空合并运算符仍然 return 为空?
Why does the Null Coalesce Operator still return null?
我有这个套路:
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
}
那么,为什么即使 SelectedSession
不是 Null,它仍然抛出 NullReferenceException
错误?
Tolerance
或 Verification
可能为空,而您正在对空指针调用 ToString()
函数。
您不能在空指针上调用 ToString()
。
空值传播运算符很棒 - 但它并不能神奇地消除空值。
这个片段
SelectedSession?.Tolerance
如果 SelectedSession
为 null 则不会出错,但它会继续传播以便上面的结果为 null。如果 SelectedSession
为 not null,但 Tolerence
为 null,则同样适用。
问题是您然后尝试在 null
上调用 ToString()
SelectedSession?.Tolerance.ToString()
我有这个套路:
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
}
那么,为什么即使 SelectedSession
不是 Null,它仍然抛出 NullReferenceException
错误?
Tolerance
或 Verification
可能为空,而您正在对空指针调用 ToString()
函数。
您不能在空指针上调用 ToString()
。
空值传播运算符很棒 - 但它并不能神奇地消除空值。
这个片段
SelectedSession?.Tolerance
如果 SelectedSession
为 null 则不会出错,但它会继续传播以便上面的结果为 null。如果 SelectedSession
为 not null,但 Tolerence
为 null,则同样适用。
问题是您然后尝试在 null
上调用ToString()
SelectedSession?.Tolerance.ToString()