使用枚举标志满足条件后无法执行正确的操作
Cannot perform correct action after condition is met using Enumeration Flags
方法:
- 员工名单
- 每个员工都有一个技能集,可以包含多个技能
- 技能集源自枚举
- 我希望能够有一个循环来读取枚举,如果它们包含适当的技能,它就会从循环中出来
代码
bool success = false;
foreach (Employee emp in employees)
{
while (emp.Busy != true || success == true)
{
if (emp.Busy == false && emp.Skills.ToString() == _skillRequired.ToString() && success == false)
{
emp.EmployeeWorkload = _jobName;
emp.ShiftsLeft = _shiftsLeft;
emp.Busy = true;
success = true;
}
else if (emp.Busy == true)
{
MessageBox.Show("Sorry there is no one available for this job");
}
问题
[Flags]
public enum MemberSkills { None = 0, CSharp = 1 << 0, SQL = 1 << 1, PHP = 1 << 2, Javascript = 1 << 3, Web = 1 << 4, Python = 1 << 5, Oracle = 1 << 6, CPlus = 1 << 7, Perl = 1 << 8 };
Employee e1 = new Employee(MemberJob.Employee, "Name", MemberSkills.CPlus | MemberSkills.CSharp, false);
Employee e2 = new Employee(MemberJob.Employee, "Another Name", MemberSkills.CSharp, false);
因为对象包含一个或多个MemberSkills
,if语句读取对象为"CSharp | CPlus",无法正确执行方法。而是选择技能集中具有 CSharp 的员工。参见 e2
由于enum是Flags,所以可以使用enum的.HasFlag方法来检查是否设置了flags。
还是老办法;您可以使用 (emp.Skills & _skillRequired) == _skillRequired 查看是否设置了所有必需的标志。
Enum
class 上有一个名为 HasFlag
的方法可以满足您的需要:
var _skillRequired = MemberSkills.CSharp;
if (emp.Skills.HasFlag(_skillRequired))
{
...
}
如果由于某种原因您无法更改 skillRequired
,您需要将值解析为枚举:
var _skillRequiredAsEnum = (MemberSkills)Enum.Parse(typeof(MemberSkills), _skillRequired));
方法:
- 员工名单
- 每个员工都有一个技能集,可以包含多个技能
- 技能集源自枚举
- 我希望能够有一个循环来读取枚举,如果它们包含适当的技能,它就会从循环中出来
代码
bool success = false;
foreach (Employee emp in employees)
{
while (emp.Busy != true || success == true)
{
if (emp.Busy == false && emp.Skills.ToString() == _skillRequired.ToString() && success == false)
{
emp.EmployeeWorkload = _jobName;
emp.ShiftsLeft = _shiftsLeft;
emp.Busy = true;
success = true;
}
else if (emp.Busy == true)
{
MessageBox.Show("Sorry there is no one available for this job");
}
问题
[Flags]
public enum MemberSkills { None = 0, CSharp = 1 << 0, SQL = 1 << 1, PHP = 1 << 2, Javascript = 1 << 3, Web = 1 << 4, Python = 1 << 5, Oracle = 1 << 6, CPlus = 1 << 7, Perl = 1 << 8 };
Employee e1 = new Employee(MemberJob.Employee, "Name", MemberSkills.CPlus | MemberSkills.CSharp, false);
Employee e2 = new Employee(MemberJob.Employee, "Another Name", MemberSkills.CSharp, false);
因为对象包含一个或多个MemberSkills
,if语句读取对象为"CSharp | CPlus",无法正确执行方法。而是选择技能集中具有 CSharp 的员工。参见 e2
由于enum是Flags,所以可以使用enum的.HasFlag方法来检查是否设置了flags。
还是老办法;您可以使用 (emp.Skills & _skillRequired) == _skillRequired 查看是否设置了所有必需的标志。
Enum
class 上有一个名为 HasFlag
的方法可以满足您的需要:
var _skillRequired = MemberSkills.CSharp;
if (emp.Skills.HasFlag(_skillRequired))
{
...
}
如果由于某种原因您无法更改 skillRequired
,您需要将值解析为枚举:
var _skillRequiredAsEnum = (MemberSkills)Enum.Parse(typeof(MemberSkills), _skillRequired));