To answer your real question:
if the switch statement has a way to fulfill all cases.
An incomprehensible way that I can think of.
task a
[Flags]
public enum TaskOptions
{
Print = 1,
Save = 2,
SendMail = 4,
}
- :
task = TaskOptions.Print | TaskOptions.Save;
if (task.HasFlag(TaskOptions.Print))
{
print();
}
if (task.HasFlag(TaskOptions.Save))
{
save();
}
if (task.HasFlag(TaskOptions.SendMail))
{
sendMail();
}
all
,
[Flags]
public enum TaskOptions
{
Print = 1,
Save = 2,
SendMail = 4,
NewOption = 8,
}
task = TaskOptions.Print | TaskOptions.Save;
if (task.HasFlag(TaskOptions.Print))
{
print();
}
if (task.HasFlag(TaskOptions.Save))
{
save();
}
if (task.HasFlag(TaskOptions.SendMail))
{
sendMail();
}
if (task.HasFlag(TaskOptions.NewOption))
{
newOption();
}
| &
= TaskOptions.Print | TaskOptions.Save. , , "", !? , - ,
. .
4 , . .
:
Print = P
Save = S
SendMail = M
NewOption = N
8 4 2 1
N M S P
task = TaskOptions.Print | TaskOptions.Save
0 0 0 1 P is declared as 1 in the enum.
0 0 1 0 S is declared as 2 in the enum.
==========
0 0 1 1 < I've "or'd" these numbers together. They now represent Print AND Save as one option. The number "3" (binary 0011) is equivalent to "print and save"
"3", , , & .
N M S P
0 0 1 1 //This is P & S
0 0 0 1 //And we want to check if it has "P"
==========
0 0 0 1 < this returns non-zero. it contains the flag!
N
N M S P
0 0 1 1 //This is P & S
1 0 0 0 //And we want to check if it has "N"
==========
0 0 0 0 < this returns zero. This state doesn't contain "N"
, , if s, :
private readonly Dictionary<TaskOptions, Action> actions =
new Dictionary<TaskOptions, Action>
{
{ TaskOptions.Print, Print },
{ TaskOptions.Save, Save },
{ TaskOptions.SendMail , SendMail }
};
...
var task = TaskOptions.Print | TaskOptions.Save;
foreach (var enumValue in Enum.GetValues(typeof(TaskOptions)).Cast<TaskOptions>())
{
if (task.HasFlag(enumValue))
{
actions[enumValue]();
}
}