[英]How can I properly define the number of different objects to create?
I have this class with these two methods and a list:我有这两个方法和一个列表的类:
public class Example
{
protected List<Person> ExampleList = new List<Person>();
public Example()
{
CreatePersonInstances();
foreach (Person personToInitialize in ExampleList)
personToInitialize.Initialize();
}
protected void CreatePersonInstances()
{
ExampleList.Add(new Employee());
ExampleList.Add(new Manager());
ExampleList.Add(new Recruiter());
}
}
How can I create properly a specific number of items from a user defined quantity?如何根据用户定义的数量正确创建特定数量的项目?
For example, if the user decides to create two employees, a manager and zero recruiters, I have to be able to create the defined quantity of objects in CreatePersonInstaces();
例如,如果用户决定创建两个员工,一个经理和零个招聘人员,我必须能够在CreatePersonInstaces();
创建定义数量的对象CreatePersonInstaces();
You could begin by adding 3 parameters in the constructor, - a parameter each signifying number of Employee/Manager/Recruiter to create.您可以首先在构造函数中添加 3 个参数,一个参数分别表示要创建的员工/经理/招聘人员的数量。
public Example(int employee,int manager,int Recruiter)
{
// Rest of code
}
You could also make your CreatePersonInstances method generic that accepts a parameter type which inherits from Person along with number of instances to create.您还可以使您的 CreatePersonInstances 方法通用,该方法接受从 Person 继承的参数类型以及要创建的实例数。
protected void CreatePersonInstances<T>(int count) where T:Person,new()
{
EmployeeList.AddRange(IEnumerable.Range(1,count).Select(x=>new T()));
}
You could now change your constructor definition as您现在可以将构造函数定义更改为
public Example(int employeeCount,int managerCount,int recruiterCount)
{
CreatePersonInstances<Employee>(employeeCount);
CreatePersonInstances<Manager>(managerCount);
CreatePersonInstances<Recruiter>(recruiterCount);
foreach (Person personToInitialize in ExampleList)
personToInitialize.Initialize();
}
protected void CreatePersonInstances(int employeeCount, int managerCount, int recruiterCount)
{
//some validation to check count number not negative
ExampleList.AddRange(Enumerable.Range(0, employeeCount).Select(x => new Employee()));
ExampleList.AddRange(Enumerable.Range(0, managerCount).Select(x => new Manager()));
ExampleList.AddRange(Enumerable.Range(0, recruiterCount).Select(x => new Recruiter()));
}
where Employee, Manager and recruiter inherit from Person entity员工、经理和招聘人员从 Person 实体继承
public class Person
{
public string Name { get; set; }
}
public class Employee : Person
{
public int EmployeeId { get; set; }
}
public class Manager : Person
{
public int ManagerId { get; set; }
}
public class Recruiter : Person
{
public int RecruiterId { get; set; }
}
Besides the scope of the question, this whole model is a good use case for the Factory Design Pattern.除了问题的范围之外,整个模型是工厂设计模式的一个很好的用例。 If you havent, check it out 👍如果你还没有,请检查一下👍
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.