how to use switch case like (if)?

自作多情 提交于 2019-12-02 17:04:29

问题


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 user 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.



来源:https://stackoverflow.com/questions/46962301/how-to-use-switch-case-like-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!