-
StackOverflow 文件
-
C# Language 教程
-
屬性
-
訪問屬性
class Program
{
public static void Main(string[] args)
{
Person aPerson = new Person("Ann Xena Sample", new DateTime(1984, 10, 22));
//example of accessing properties (Id, Name & DOB)
Console.WriteLine("Id is: \t{0}\nName is:\t'{1}'.\nDOB is: \t{2:yyyy-MM-dd}.\nAge is: \t{3}", aPerson.Id, aPerson.Name, aPerson.DOB, aPerson.GetAgeInYears());
//example of setting properties
aPerson.Name = " Hans Trimmer ";
aPerson.DOB = new DateTime(1961, 11, 11);
//aPerson.Id = 5; //this won't compile as Id's SET method is private; so only accessible within the Person class.
//aPerson.DOB = DateTime.UtcNow.AddYears(1); //this would throw a runtime error as there's validation to ensure the DOB is in past.
//see how our changes above take effect; note that the Name has been trimmed
Console.WriteLine("Id is: \t{0}\nName is:\t'{1}'.\nDOB is: \t{2:yyyy-MM-dd}.\nAge is: \t{3}", aPerson.Id, aPerson.Name, aPerson.DOB, aPerson.GetAgeInYears());
Console.WriteLine("Press any key to continue");
Console.Read();
}
}
public class Person
{
private static int nextId = 0;
private string name;
private DateTime dob; //dates are held in UTC; i.e. we disregard timezones
public Person(string name, DateTime dob)
{
this.Id = ++Person.nextId;
this.Name = name;
this.DOB = dob;
}
public int Id
{
get;
private set;
}
public string Name
{
get { return this.name; }
set
{
if (string.IsNullOrWhiteSpace(value)) throw new InvalidNameException(value);
this.name = value.Trim();
}
}
public DateTime DOB
{
get { return this.dob; }
set
{
if (value < DateTime.UtcNow.AddYears(-200) || value > DateTime.UtcNow) throw new InvalidDobException(value);
this.dob = value;
}
}
public int GetAgeInYears()
{
DateTime today = DateTime.UtcNow;
int offset = HasHadBirthdayThisYear() ? 0 : -1;
return today.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;
}
}
public class InvalidNameException : ApplicationException
{
const string InvalidNameExceptionMessage = "'{0}' is an invalid name.";
public InvalidNameException(string value): base(string.Format(InvalidNameExceptionMessage,value)){}
}
public class InvalidDobException : ApplicationException
{
const string InvalidDobExceptionMessage = "'{0:yyyy-MM-dd}' is an invalid DOB. The date must not be in the future, or over 200 years in the past.";
public InvalidDobException(DateTime value): base(string.Format(InvalidDobExceptionMessage,value)){}
}