使用List中的数组 - OOP - Generic List

时间:2015-12-16 23:24:12

标签: c# list oop

我创建了一个列表:

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; } 
}

我希望能够输入尽可能多的技能&#39;正如我现在所想的那样,因为我使用了枚举,所以只能在Employee e1中输入一项技能。

我如何设置一系列技能&#39;在列表/构造函数中?

2 个答案:

答案 0 :(得分:6)

您可以使用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(); }
    }

    ...
}

答案 1 :(得分:3)

传递Skills[]的替代方法,您可以将enum更改为员工技能的一点掩饰:

[Flags]
enum Skills
{
   None = 0,
   CSharp = 1 << 0,
   SQL = 1 << 1,
   PHP = 1 << 2,
   Javascript = 1 << 3,
   ...
}

然后,可以将个人技能按位进行OR运算,以创建单个员工的技能:

Employee e1 = new Employee(Job.Employee, "Name", Skills.CSharp | Skills.SQL | Skills.PHP );

然后,要检查员工是否具有特定技能,您可以使用Enum.HasFlag方法,例如:

if( e1.Skills.HasFlag( Skills.CSharp ) )