深入理解 c# 第四章 一个包括计算年龄的人物类

    class AgeCalculation
    {
        class Person
        {
            DateTime birth;
            DateTime? death;
            string name;

            public TimeSpan Age
            {
                get
                {
                    if (death == null)  //检查HasValue
                    {
                        return DateTime.Now - birth;
                    }
                    else
                    {
                        return death.Value - birth;  //拆包进行计算
                    }
                }
            }

            public Person(string name,
                          DateTime birth,
                          DateTime? death)  //可空
            {
                this.birth = birth;
                this.death = death;  //null 可以赋值,并且通过编译
                this.name = name;
            }
        }

        static void Main()
        {
            Person turing = new Person("Alan Turing",
                                       new DateTime(1912, 6, 23),
                                       new DateTime(1954, 6, 7));  //包装成可空实例
            Person knuth = new Person("Donald Knuth",
                                       new DateTime(1938, 1, 10),
                                       null);  //指定死亡日期为 null
        }
    }


实例化一个类 调用类的构造函数,因为DateTime death 可空,null值就可以赋值,可以通过编译

无输出   能通过编译


你可能感兴趣的:(深入理解 c# 第四章 一个包括计算年龄的人物类)