xiacy

导航

4.3.2 使用null进行赋值和比较

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

        public TimeSpan Age
        {
            get
            {
                if (death.HasValue)
                   return death.Value - birth;
                else
                    return DateTime.Now - birth; 
            }
        }

        public Person(string name, DateTime birth, DateTime? death)
        {
            this.birth = birth;
            this.death = death;
            this.name = name;
        }
    }

    class Program
    {
        
        static void Main(string[] args)
        {
            Person turing = new Person("Alan Turing", new DateTime(1912, 6, 2), new DateTime(1954, 6, 7));
            Console.WriteLine(turing.Age.Days/365);
            Person knuth = new Person("Donald Knuth", new DateTime(1938, 1, 10), null);
            Console.WriteLine();
            Console.WriteLine(knuth.Age.Days/365);
            Console.ReadKey();
        }
    }

 

posted on 2012-05-01 15:16  xiacy  阅读(186)  评论(0编辑  收藏  举报