c# 对象封装时get、set 简单的对属性值的处理

案例说明:赋值人这个对象的属性-出生日期,根据属性出生日期内部自动计算出年龄

封装的对象

using System;

namespace Demo.Model
{
    /// <summary>
    /// 对象人
    /// </summary>
    public class Person
    {
        private static int age;
        private static DateTime birthDate;

        /// <summary>
        /// 编号
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }


        /// <summary>
        /// 生日
        /// </summary>
        public DateTime BirthDate
        {
            get { return birthDate; }
            set
            {
                birthDate = value;
                CalculateAge(birthDate);
            }
        }
        /// <summary>
        /// 年龄
        /// </summary>
        public int Age
        {
            get { return age; }
            set
            {
                if (value != null)//value就是赋值时传进来的值
                {
                    age = value;
                }
            }
        }
        /// <summary>
        /// 根据生日计算年龄
        /// </summary>
        /// <param name="BirthDate"></param>
        public void CalculateAge(DateTime BirthDate)
        {
            DateTime nowDateTime = DateTime.Now;
            int timeNum = nowDateTime.Year - BirthDate.Year;
            //现在日期减去出生日期,再判断是否满周岁,不满周岁则减去
            age = timeNum += (nowDateTime.Month < BirthDate.Month ||
                               (nowDateTime.Month == BirthDate.Month && nowDateTime.Day < BirthDate.Day))
                ? -1//满周岁
                : 0;//不满周岁
        }
    }
}

控制台调用

using Demo.Model;
using System;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var person = GetPerson();
        }

        static object GetPerson()
        {
            var dataTime = Convert.ToDateTime("1998-09-18");
            return new Person {BirthDate = dataTime ,Age = 100};

        }

    }

    
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值