所以我想找一个学校班上最年长的人。年龄根据他的个人代码计算。例如,120499-12345,其中第一部分是日期,而第一部分是" - "可以是1或2,取决于何时出生(2000年之前 - " 1",2000之后 - " 2")。个人代码是字符串类型,我使用子字符串从代码中获取年份,使用1或2来计算年龄。问题是我真的不懂如何找到最老的人。
public void Oldest()
{
int age = 0;
foreach (Student b in students)// students is an array of Student class
{
string sub1 = b.pers_code.Substring(4, 2);
string sub2 = b.pers_code.Substring(7, 1);
int type = 0;
type = Convert.ToInt32(sub2);
int year = 0;
year = Convert.ToInt32(sub1);
if (type == 2)
{
age = 18 - year;
}
else
{
age = 2018 - (year + 1900);
}
}
}
答案 0 :(得分:3)
我真的不懂如何找到最老的人
当然,你的方法太多了。您可以采用不同的方法并首先改进总体设计,而不是尝试修复它。
您可以将i-m-responsible-for-everything方法拆分为单一功能:
DateTime GetBirthDate(string personCode) { ... }
TimeSpan GetAge(DateTime birthDate) { ... }
现在您可以单独测试此逻辑。
想想看,实际上Student
有责任了解他或她的年龄。
class Student
{
...
// instead of computing, you can set these once in the constructor
public DateTime BirthDay => GetBirthDay(this.PersonalCode);
public TimeSpan Age => GetAge(this.BirthDay);
...
private TimeSpan GetAge(DateTime birthDate) { ... }
}
然后,您可以将简单且可测试的构建块组装成更大的解决方案
var oldest = students.OrderByDescending(s => s.Age).FirstOrDefault();
var maxAge = students.Max(s => s.Age);
这一切都变得更加清晰,更不用说我们现在能够轻松找到其他统计数据 - 平均年龄,前10名最年轻的学生等。