所以我有一个对象列表(AllCompanies),列表中的所有对象都继承自同一个类(公司)。而且我在类中也有一个字段,它们都是继承的,完全是另一个类(Employees)。我想创建一个当前活动的每个Employee的列表,并且我将每个公司都放在一个对象列表中。正如您在下面看到的,我试图简单地将Employee的字段添加到列表中,但是我收到错误,因为我试图将对象转换为员工列表。
public class Main()
{
List<List<Employee>> AllEmployees = new List<List<Employee>>();
List<object> AllCompanies = new List<object>() { new SmallCompany(), new LargeCompany(), new SmallCompany() };
AllCompanies.ForEach(delegate(object o)
{
// - Here's the problem.
AllEmployees.Add(o.GetType().GetField("Employees").GetValue(o));
// - Here's the problem.
});
}
class Employee
{
public string Name;
public int Age;
public Employee(string name, int age)
{
Name = name;
Age = age;
}
}
class Company
{
public List<Employee> Employees = new List<Employee>();
}
class SmallCompany : Company
{
public SmallCompany(){}
}
class LargeCompany : Company
{
public LargeCompany(){}
}
如何最有效地完成这项工作?
答案 0 :(得分:5)
您不应该将列表键入object
类型的列表。对象都是Company
个对象,列表应该反映出来。
List<Company> AllCompanies = new List<Company>()
{
new SmallCompany(),
new LargeCompany(),
new SmallCompany()
};
这将消除对任何可能使生活变得艰难的可怕反射代码的需要。
一旦你将每个项目投射到一个新项目,给定一个选择器很容易做到:
var allEmployees = AllCompanies.Select(company => company.Employees);
答案 1 :(得分:0)
我不知道我是否理解你真正想要的东西,但如果我这样做,在我看来,这将是更容易理解和更容易的解决方案:
class Program
{
static void Main(string[] args)
{
List<ICompany> AllCompanies = new List<ICompany>();
AllCompanies.Add(new Company());
AllCompanies.Add(new SmallCompany());
AllCompanies.Add(new LargeCompany());
List<Employee> AllEmployees = new List<Employee>();
foreach(var Company in AllCompanies)
{
Company.Employees.ForEach((Employee)=>
{
if(Employee.IsActive)
AllEmployees.Add(Employee);
});
}
}
}
class Employee
{
public string Name;
public int Age;
public bool IsActive;
public Employee(string name, int age)
{
Name = name;
Age = age;
}
}
interface ICompany
{
List<Employee> Employees { get; set; }
}
class Company: ICompany
{
public List<Employee> Employees { get; set; }
}
class SmallCompany : ICompany
{
public List<Employee> Employees { get; set; }
}
class LargeCompany : ICompany
{
public List<Employee> Employees { get; set; }
}