连接字符串和 Is 运算符

问题描述 投票:0回答:1

我不明白为什么这段代码会抛出空引用。 我认为这与“加”运算符和“是”运算符的优先级有关,但我真的不确定为什么。

 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";
 }
c# operators
1个回答
2
投票

嗯,问题出在执行顺序上:

"somestring " + B is not null  ? $" {B.Property}" : "empty
  1. "somestring " + B
    (将是
    "something " + null == "something "
  2. "somestring " is not null
    true
    ,因为
    "something"
    不为空)
  3. $" {B.Property}
    - 抛出异常,因为
    B
    null

让我们添加括号来显示实际顺序:

(("somestring " + B) is not null) ? $" {B.Property}" : "empty

在第二个版本中

"somestring " + (B is not null ? $" {B.Property}" : "empty")

我们有不同的订单

  1. (B is not null ? $" {B.Property}" : "empty")
    -
    "empty"
    ,因为
    B
    null
  2. "somestring " + "empty" == "something empty"
© www.soinside.com 2019 - 2024. All rights reserved.