我的任务指定我必须创建6个类,现在在这些类中的一个调用(播放器),其中包含通常的名称,性别等!必须有一种方法可以在几年内返回玩家的年龄。现在我写了下面的代码,但是我觉得它可能不需要太长时间,所以我正在寻找任何有用的建议。C#类和返回值
class Player
{
private string firstName;
private string lastName;
private List<string> middleNames;
private DateTime birthday;
private string nationality;
private string gender;
public Player(string firstName, string lastName, List<string> middleNames, DateTime birthday, string nationality, string gender)
{
this.firstName = firstName;
this.lastName = lastName;
this.middleNames = middleNames;
this.birthday = birthday;
this.nationality = nationality;
this.gender = gender;
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
public List<string> MiddleNames
{
get
{
return middleNames;
}
set
{
middleNames = value;
}
}
public DateTime BirthDay
{
get
{
return birthday;
}
set
{
birthday = value;
}
}
public string Nationality
{
get
{
return nationality;
}
set
{
nationality = value;
}
}
public string Gender
{
get
{
return gender;
}
set
{
gender = value;
}
}
public int GetAge(DateTime currentDate)
{
int age = currentDate.Year - birthday.Year;
if (currentDate.Month - birthday.Month < 0 || (currentDate.Month - birthday.Month == 0 && currentDate.Day - birthday.Day < 0))
{
--age;
}
return age;
}
}
首先要了解的是:自动实现的属性。你有71行代码,可以用6表示。接下来,我建议使用我的[Noda Time项目](http://nodatime.org),这使得执行基于日期的计算变得更容易。现在,这与你的问题标题有什么关系?这真的只是*关于“我如何计算一个时代”? –
如果是这样,这是一个https://stackoverflow.com/questions/9重复 - 网站上最古老的问题之一... –
@JonSkeet他们说这是一个任务,推动一个库isn没有帮助。 这就是说,这更多的是一个样式问题,而不是一个实际的编程问题,可能不属于 –