C#上下文中的各种属性
示例
public class Person
{
//id属性可以由其他类读取,但只能由Person类设置
public int Id {get; private set;}
//可以检索或分配Name属性
public string Name {get; set;}
private DateTime dob;
//出生日期属性存储在私有变量中,但可以通过公共属性检索或分配。
public DateTime DOB
{
get { return this.dob; }
set {this.dob= value; }
}
//Age属性只能被检索;它的值是从出生日期算起的
public int Age
{
get
{
int offset = HasHadBirthdayThisYear() ? 0 : -1;
return DateTime.UtcNow.Year - this.dob.Year + offset;
}
}
//这不是属性而是方法;尽管可以根据需要将其重写为属性。
private bool HasHadBirthdayThisYear()
{
bool hasHadBirthdayThisYear = true;
DateTime today = DateTime.UtcNow;
if (today.Month > this.dob.Month)
{
hasHadBirthdayThisYear = true;
}
else
{
if (today.Month == this.dob.Month)
{
hasHadBirthdayThisYear =today.Day> this.dob.Day;
}
else
{
hasHadBirthdayThisYear = false;
}
}
return hasHadBirthdayThisYear;
}
}
热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短