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;
}
}
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短