-
StackOverflow 文档
-
C# Language 教程
-
属性
-
语境中的各种属性
public class Person
{
//Id property can be read by other classes, but only set by the Person class
public int Id {get; private set;}
//Name property can be retrieved or assigned
public string Name {get; set;}
private DateTime dob;
//Date of Birth property is stored in a private variable, but retrieved or assigned through the public property.
public DateTime DOB
{
get { return this.dob; }
set { this.dob = value; }
}
//Age property can only be retrieved; it's value is derived from the date of birth
public int Age
{
get
{
int offset = HasHadBirthdayThisYear() ? 0 : -1;
return DateTime.UtcNow.Year - this.dob.Year + offset;
}
}
//this is not a property but a method; though it could be rewritten as a property if desired.
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;
}
}