Use string.Contains() with switch()

前端 未结 12 2128
抹茶落季
抹茶落季 2020-12-25 10:39

I\'m doing an C# app where I use

if ((message.Contains(\"test\")))
{
   Console.WriteLine(\"yes\");
} else if ((message.Contains(\"test2\"))) {
   Console.W         


        
12条回答
  •  抹茶落季
    2020-12-25 11:02

    Some custom swtich can be created like this. Allows multiple case execution as well

    public class ContainsSwitch
    {
    
        List actionList = new List();
        public string Value { get; set; }
        public Action Action { get; set; }
        public bool SingleCaseExecution { get; set; }
        public void Perform( string target)
        {
            foreach (ContainsSwitch act in actionList)
            {
                if (target.Contains(act.Value))
                {
                    act.Action();
                    if(SingleCaseExecution)
                        break;
                }
            }
        }
        public void AddCase(string value, Action act)
        {
            actionList.Add(new ContainsSwitch() { Action = act, Value = value });
        }
    }
    

    Call like this

    string m = "abc";
    ContainsSwitch switchAction = new ContainsSwitch();
    switchAction.SingleCaseExecution = true;
    switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
    switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
    switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
    
    switchAction.Perform(m);
    

提交回复
热议问题