C# 6.0 Null Propagation Operator & Property Assignment

后端 未结 3 1953
情歌与酒
情歌与酒 2020-12-03 20:43

This question has been completely overhauled in the interest of being thorough in explanation.

I have noticed what appears to be quite a poor limitation of

3条回答
  •  猫巷女王i
    2020-12-03 21:09

    Try it like this...

    using System;
    
    namespace TestCon
    {
        class Program
        {
            public static void Main()
        {
    
            Person person = null;
            //Person person = new Person() { Name = "Jack" };
    
            //Using an "if" null check.
            if (person != null)
            {
                Console.WriteLine(person.Name);
                person.Name = "Jane";
                Console.WriteLine(person.Name);
            }
    
            //using a ternary null check.
            string arg = (person != null) ? person.Name = "John" : arg = null;
            //Remember the first statment after the "?" is what happens when true. False after the ":". (Just saying "john" is not enough)
            //Console.WriteLine(person.Name);
    
            if (arg == null)
            {
                Console.WriteLine("arg is null");
            }
    
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    public class Person
    {
        public string Name { get; set; }
    }
    

    }

提交回复
热议问题