1、调用
class Program
{
static void Main(string[] args)
{
//实例化一个学生对象
Student s = new Student("张三", new DateTime(1994,1,29));
//输出该学生姓名 生日 年龄
Console.WriteLine($"姓名:{s.Name},生日:{s.Birthday},年龄:{s.Age}");
// s.Age = 30;错误用法年龄只能获取,会语法错误
Console.ReadLine();
}
}
2、学生对象
public class Student
{
public Student(string name, DateTime birthday)
{
this.Name = name;
this.Birthday_Custom = birthday;
}
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 生日
/// </summary>
public string Birthday { get; private set; }
private DateTime Birthday_Custom
{
set
{
//格式化生日日期
this.Birthday = value.ToString("yyyy-MM-dd");
//自动计算年龄
int year = DateTime.Now.Year - value.Year;
if (DateTime.Now.Month < value.Month)//未满一年
{
year--;
}
this.Age = year;
}
}
/// <summary>
/// 年龄
/// </summary>
public int Age { get; private set; }
}
3、结果