C # execute all cases in switch statement

I have a switch statement as shown below:

switch(task)
    {
        case 1:
            print();
            break;
        case 2:
            save();
            break;
        case 3:
            sendmail();
            break;
    }

I need a way to complete all cases, which means that if the task is (all) I want to print, save and send mail. Is this possible with some modification in this case? I know this, I can do it as follows:

case All:
    print();
    save();
    sendmail();
    break;

But, as I said, I want to know if there is a way to execute all cases in the switch statement. thanks in advance

+4
source share
6 answers

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,
    //Note that these numbers go up in powers of two
}

- :

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]();
    }
}
+9

, , switch:

class FallSwitch 
{
     SortedDictionary<int, Action> _cases = new SortedDictionary<int, Action>();

    public void AddCaseAction(int @case, Action action)
    {
        if (_cases.ContainsKey(@case)) throw ArgumentException("case already exists");
        _cases.Add(@case, action);
    }

    public void Execute(int startCase)
    {
        if (!_cases.ContainsKey(startCase)) throw ArgumentException("case doesn't exist");
        var tasks = _cases.Where(pair => pair.Key >= startCase);
        tasks.ForEach(pair => pair.Value());
    }
}

:

var fs = new FallSwitch();
fs.AddCaseAction(0, () => Console.WriteLine("0"));
fs.AddCaseAction(1, () => Console.WriteLine("1"));
fs.AddCaseAction(2, () => Console.WriteLine("2"));
fs.AddCaseAction(6, () => Console.WriteLine("6"));

fs.Execute(1);
+1

.

, . foreach-loop , . .

[Flags]
public enum TaskOptions 
{
    Print    = 1,
    Save     = 2,
    SendMail = 4
}

// In the clase where print(), save() and sendmail() are declared
private readonly Dictionary<TaskOptions, Action> _tasks;

public Ctor()
{
    _tasks = new Dictionary<TaskOptions, Action>
        {
            { TaskOptions.Print, this.print },
            { TaskOptions.Save, this.save },
            { TaskOptions.SendMail, this.sendmail }
        };
}

public void Do(TaskOptions tasksToRun)
{
    foreach (var action in from taskOption in Enum.GetValues(typeof(TaskOptions)).Cast<TaskOptions>()
                           where tasksToRun.HasFlag(taskOption)
                           orderby taskOption // only to specify it in the declared order
                           select this._tasks[taskOption])
    {
        action();
    }
}

, , . , .

+1

, # , goto , case -, .

"all" , goto , :

switch(task)
{
  case 1: case 0;//I don't know what "all" is, so I'm using 0 here
    print();
    if (task == 0) goto case 2;
    break;
  case 2:
    save();
    if (task == 0) goto case 3;
    break;
  case 3:
    sendmail();
    break;
}
0

- . , . , . switch . , - 4- , 1,2 4.

 RunTasks(new[] {new PrintTask(), new SaveTask(), new SendMailTask()});

 void RunTasks(int[] tasks)
 {
     foreach (var task in tasks)
     {
         task.Run();
     }
 }

 interface ITask
 {
     void Run();
 }

 class PrintTask : ITask
 {
      public void Run()
      {
          ....
      }
  }

  // etc...
0

,

switch(task)
{
    case 1:
        print();
        break;
    case 2:
        save();
        break;
    case 3:
        sendmail();
        break;
    case 4:
        print();
        save();
        sendmail();
        break;
}

Alternatively, you can set a default case to execute all cases

 switch(task)
{
    case 1:
        print();
        break;
    case 2:
        save();
        break;
    case 3:
        sendmail();
        break;
    default:
        print();
        save();
        sendmail();
        break;
}

None of these methods are very neat, I think this is probably the easiest solution to your problem.

0
source

Source: https://habr.com/ru/post/1607790/


All Articles