我在任务计划程序类中有以下枚举值,而我正在创建一个任务,我需要根据复选框选择添加一周中的几天。如果选中星期一复选框,我只需要在星期一通过(如果同时选中其他复选框,则需要多天)。
在下面的代码中,如何动态传递多天?
public enum DaysOfTheWeek: short
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
AllDays = 127
}
DaysOfWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Sunday;
答案 0 :(得分:1)
您可以像这样循环选择列表并创建枚举值:
var days = new[] {1, 4, 32};
var daysOfTheWeek = DaysOfTheWeek.None;
foreach (var day in days)
{
daysOfTheWeek = daysOfTheWeek | (DaysOfTheWeek) day;
}
[Flags]
public enum DaysOfTheWeek
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
AllDays = 128
}
答案 1 :(得分:0)
您的问题没有提及循环,但您对我的评论的回复确实如此。你的意思是:
DaysOfWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Sunday;
foreach (int day in Enum.GetValues(typeof(DaysOfTheWeek)))
{
if ( day & DaysOfWeek ) {
/* do something for this day */
}
}
答案 2 :(得分:0)
使用Flags
属性装饰你的枚举:
[Flags]
public enum DaysOfTheWeek : short
声明一个DaysOfTheWeek
变量并将其初始化为零:
DaysOfTheWeek days = 0;
为每天勾选的枚举值添加标记。将bool sunday = true, wednesday = true;
替换为您的代码,该代码会检查复选框:
bool sunday = true, wednesday = true; // this is just proof of concept
if (sunday)
days |= DaysOfTheWeek.Sunday;
if (wednesday)
days |= DaysOfTheWeek.Wednesday;
days
输出:
周日,周三
答案 3 :(得分:0)
正如 Shahriar Gholami 所建议的那样,这里有完整的代码:
class Program
{
static void Main(string[] args)
{
var daysOfWeek = GetDaysOfTheWeek(new List<DaysOfTheWeek> {DaysOfTheWeek.Monday, DaysOfTheWeek.Sunday});
Console.WriteLine(daysOfWeek); //3
}
public static DaysOfTheWeek GetDaysOfTheWeek(List<DaysOfTheWeek> selectedDays)
{
var daysOfTheWeek = DaysOfTheWeek.None;
foreach (var day in selectedDays)
{
daysOfTheWeek = daysOfTheWeek | day;
}
return daysOfTheWeek;
}
}
[Flags]
public enum DaysOfTheWeek : short
{
None = 0,
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
AllDays = 127
}