示例
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;
}
}