如何使用开关盒(如果)? [英] how to use switch case like (if)?
本文介绍了如何使用开关盒(如果)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想像我的代码中那样使用switch,但是我不知道如何使用&&以防万一 ! 这是我的代码
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;
}
推荐答案
如果可以使用更高版本的C#,则可以这样编写:
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.
}
在您的特定情况下,无需引入新的局部变量(s
),因此代码可以写为
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.
}
您可以在 MSDN 上进行阅读a>.
You can read about it on MSDN.
这篇关于如何使用开关盒(如果)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文