我不明白为什么这段代码会抛出空引用。 我认为这与“加”运算符和“是”运算符的优先级有关,但我真的不确定为什么。
return "somestring " + B is not null ? $" {B.Property}" : "empty";
完整样本:
internal class Program
{
static void Main(string[] args)
{
var a = new A();
Console.WriteLine(a.ToString());
Console.ReadKey();
}
}
public class A
{
public B? B { get; set; }
public override string ToString()
{
return "somestring " + B is not null ? $" {B.Property}" : "empty"; //nullref
return "somestring " + (B is not null ? $" {B.Property}" : "empty"); //works
}
}
public class B
{
public string Property { get; set; } = "Property";
}
嗯,问题出在执行顺序上:
"somestring " + B is not null ? $" {B.Property}" : "empty
"somestring " + B
(将是"something " + null == "something "
)"somestring " is not null
(true
,因为 "something"
不为空)$" {B.Property}
- 抛出异常,因为 B
是 null
让我们添加括号来显示实际顺序:
(("somestring " + B) is not null) ? $" {B.Property}" : "empty
在第二个版本中
"somestring " + (B is not null ? $" {B.Property}" : "empty")
我们有不同的订单
(B is not null ? $" {B.Property}" : "empty")
- "empty"
,因为 B
是 null
。"somestring " + "empty" == "something empty"