代码之家  ›  专栏  ›  技术社区  ›  BlueRaja - Danny Pflughoeft

为什么空条件运算符更改常规属性访问?

  •  4
  • BlueRaja - Danny Pflughoeft  · 技术社区  · 7 年前

    我对空条件运算符如何与普通属性访问级联感到困惑。举两个例子:

    a?.b.c
    (a?.b).c
    

    a?.b 那么 result.c a == null ,则应引发异常。

    null ,意思是和 a?.b?.c .

    2 回复  |  直到 7 年前
        1
  •  9
  •   Camilo Terevinto Chase R Lewis    7 年前

    这只是运算符优先级的问题。我们来看看这些案子:

    a?。b、 c

    1. a => null 返回,则不计算任何其他值 the null-conditional operators are short-circuiting .

    1. 评估 无效的 返回
    2. ((B)null).c => NullReferenceException 被抛出

    为了使这些情况相等,您应该进行比较

    1. a?.b.c
    2. (a?.b)?.c
    3. a?.b?.c (如你所说)
        2
  •  1
  •   Grant Winney    7 年前

    除了Camilo已经提供的功能之外,我不知道这是否有用,但是下面是一个简短的比较,展示了如果没有空条件运算符的话,逻辑可能看起来如何。

    public class Program
    {
        public static void Main()
        {
            A a;
    
            a = new A { b = new B { c = 5 } };
    
            Console.WriteLine(a?.b.c);        // returns 5;
            Console.WriteLine((a?.b).c);      // returns 5;
    
            a = null;
    
            Console.WriteLine(a?.b.c ?? -1);  // returns -1;
            Console.WriteLine((a?.b).c);      // throws NullReferenceException
    
    
            // Similar to a?.b.c
    
            if (a != null)
                Console.WriteLine(a.b.c);     // returns 5;
            else
                Console.WriteLine(-1);        // returns -1;
    
    
            // Similar to (a?.b).c
    
            B tmp;
            if (a != null)
                tmp = a.b;
            else
                tmp = null;
    
            Console.WriteLine(tmp.c);         // returns 5 or throws NullReferenceException
        }
    }
    
    
    public class A
    {
        public B b { get; set; }
    }
    
    public class B
    {
        public int c { get; set; }
    }
    
    推荐文章