我对递归比较陌生。我遇到了一个奇怪的情况。正如您在下面看到的,我正在为一个复杂的部门填充员工。复杂的部门可以拥有一个或多个简单的部门和复杂的部门。它还有一个雇员的集合(列表)。当我通过这个调试时,第一个部门是复杂的,所以它进行递归,在那里我看到员工正确填充,员工收集计数是2,但是当它来自递归调用的员工集合计数再次设置为零。关于我在这里做错了什么的想法?
private void PopulateEmployees(ComplexDepartment complex)
{
foreach (var dep in complex.Departments)
{
if (dep is SimpleDepartment)
{
var simple = dep as SimpleDepartment;
complex.employees.Add(GetEmployee(simple));
}
else if (dep is ComplexDepartment)
{
PopulateEmployees(dep as ComplexDepartment);
}
}
}
private Employee GetEmployee(SimpleDapartment simple)
{
var employee = new Employee();
// some code here
return employee;
}
答案 0 :(得分:1)
private void PopulateEmployees(ComplexDepartment complex)
{
foreach (var dep in complex.Departments)
{
if (dep is SimpleDepartment)
{
var simple = dep as SimpleDepartment;
complex.employees.Add(GetEmployee(simple));
}
else if (dep is ComplexDepartment)
{
PopulateEmployees(dep as ComplexDepartment);
// you need this here, because you collect the additional employees in dep
complex.employees.AddRange(dep.employees);
}
}
}
private void PopulateEmployees(ComplexDepartment complex, ComplexDepartment addTo)
{
foreach (var dep in complex.Departments)
{
if (dep is SimpleDepartment)
{
var simple = dep as SimpleDepartment;
addTo.employees.Add(GetEmployee(simple));
}
else if (dep is ComplexDepartment)
{
PopulateEmployees(dep as ComplexDepartment, addTo);
}
}
}
// Call it like
PopulateEmployees(myDep, myDep);
private IEnumerable<Employee> EnumerateEmployees(ComplexDepartment complexDepartment)
{
foreach (var department in complexDepartment.Departments)
{
if (department is SimpleDepartment)
yield return GetEmployee((SimpleDepartment) department);
else if (department is ComplexDepartment)
{
foreach(var e in EnumerateEmployees(department))
yield return e;
}
}
}
但是如果您的结构非常深,那么您可能会遇到StackOverflows的问题 - 所以我建议使用累加器或仅使用LINQ。
代码只是为了演示如何使用递归来实现;)