在列表-OOP-泛型列表中使用数组
本文关键字:列表 数组 泛型 -OOP- | 更新日期: 2023-09-27 18:27:03
我创建了一个列表:
List<Employee> employees = new List<Employee();
我想实现这一点:
Employee e1 = new Employee(Job.Employee, "Name", "C Sharp", "Oracle", "SQL");
我现在有这个:
Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp);
这是Employee
类内的代码
public enum Job { Employee, Supervisor, Administrator };
public enum Skills {CSharp, SQL, PHP, Javascript, Web, Python, Oracle, CPlus, Perl };
protected Job job;
protected String employeeName;
protected String employeeName;
public Job Job
{
get { return job; }
protected set { job = value; }
}
public String EmployeeName
{
get { return employeeName; }
protected set { employeeName = value; }
}
public Skills Skills
{
get {return skills; }
}
我希望能够输入尽可能多的"技能",因为目前,在员工e1中只能输入一项技能,因为我使用了枚举。
如何在列表/构造函数中放入一组"技能"?
您可以使用params
数组参数将可变数量的Skills
参数传递给构造函数:
public Employee(Job job, string name, params Skills[] skills)
您还必须修改skills
字段以容纳Skills
的集合,而不是单个集合。如果在创建员工后不添加/删除技能,则可以将其设置为数组;如果需要修改集合,则可以设置为IList<Skills>
。
例如:
public class Employee
{
private List<Skills> _skills; // skills stored as a private List
// to allow modification inside Employee class
public Employee(Job job, string name, params Skills[] skills)
{
_skills = new List<Skills>(skills);
...
}
public IReadOnlyList<Skills> Skills // publicly visible as a read-only list
{
get { return _skills.AsReadOnly(); }
}
...
}
作为传递Skills[]
的替代方案,您可以将enum
更改为员工所具备技能的一个小面具:
[Flags]
enum Skills
{
None = 0,
CSharp = 1 << 0,
SQL = 1 << 1,
PHP = 1 << 2,
Javascript = 1 << 3,
...
}
然后,可以将个人技能按位或位组合在一起,以创建单个员工所具备的技能:
Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp | Skills.SQL | Skills.PHP );
然后,为了检查员工是否具有特定技能,可以使用Enum.HasFlag
方法,例如:
if( e1.Skills.HasFlag( Skills.CSharp ) )