我不明白为什么这段代码会抛出 nullref。我认为这与“加”运算符和“是”运算符的优先级有关,但我真的不确定为什么。
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
(将"something " + null == "something "
)"somestring " is not null
(true
,因为"something "
不为空)$" {B.Property}"
-抛出异常B
,因为null
让我们添加括号来显示实际顺序:
在第二个版本中
我们有不同的顺序
(B is not null ? $" {B.Property}" : "empty")
-"empty"
,因为B
是null
。"somestring " + "empty" == "something empty"