我不明白为什么这段代码会抛出 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";
}