how to use switch case like (if)?

2020-05-04 10:42发布

问题:

I want to use switch like if in my code but I dont know how to use && in case ! this is my code

string a;
a = System.Convert.ToString(textBox1.Text);

if (a.Contains('h') && a.Contains('s'))
{
    this.BackColor=Color.Red;
}
else if (a.Contains('r') && a.Contains('z')) 
{
    this.BackColor=Color.Black;

}

else if (a.Contains('a') && a.Contains('b'))
{
    this.BackColor = Color.Pink;

}

回答1:

If you can use the later versions of C# you can write it like this:

switch (st)
{
     case var s when s.Contains("asd") && s.Contains("efg"):
         Console.WriteLine(s);
         break;
     case var s when s.Contains("xyz"):
         break;
     // etc.
}

In your particular situation there is no need to introduce new local variables (s) so the code could be written as

switch(st)
{
     case var _ when st.Contains("asd") && st.Contains("efg"):
         Console.WriteLine(st);
         break;
     case var _ when st.Contains("xyz"):
         break;
     // etc.
}

You can read about it on MSDN.