How can I compare multiple variables to a single condition?

后端 未结 7 789
时光取名叫无心
时光取名叫无心 2020-12-19 16:06

I have this:

if (input.Text.ToUpper() == \"STOP\")

But there are so many possible values that I wouldn\'t be able to specify them all sepa

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 16:35

    Perfect situation for a string extension

    Add this to a new file

    namespace appUtils
    {
        public static class StringExtensions
        {
            public static bool In(this string s, params string[] values)
            {
                return values.Any(x => x.Equals(s));
            }
        }
    }
    

    and call from your code in this way

    if(input.Text.In("STOP", "END", "NO", "YES") == true)
       // ... do your stuff
    

提交回复
热议问题