C#中的可空类型

public class Person {

        public DateTime birth;

        public DateTime? death;

        string name;

        public TimeSpan Age {

            get {

                if (!death.HasValue) {

                    return DateTime.Now - birth;

                }

                else {

                    return death.Value - birth;

                }

            }

        }



        public TimeSpan Age1 {

            get {

                DateTime lastAlive = death.HasValue ? DateTime.Now : death.Value;

                return birth - lastAlive;

            }

        }



        public TimeSpan Age2 {

            get {

                return (death ?? DateTime.Now) - birth;

            }

        }

        //构造函数

        public Person(string name, DateTime birth, DateTime? death) {

            this.birth = birth;

            this.death = death;

            this.name = name;

        }

    }

  

Person tr = new Person("AAAA", new DateTime(1988, 12, 13),null); Person kk = new Person("BBBB", new DateTime(1912, 12, 13), new DateTime(1954, 12, 12)); Console.ReadKey();

  -

你可能感兴趣的:(C#)