[英]How can I make loop instead of switch statement?
我该如何写得更短? 对于每种情况,我都必须写这个,然后太长了,因为有48个数字,所以我需要48个案例。 有办法循环吗?
switch (ballBounce.ToString())
{
case "1":
if (ballBounce == n0)
{
textBox1.Text = number.ToString();
}
break;
case "2":
if (ballBounce == n1)
{
textBox1.Text = number.ToString();
}
break;
case "3":
if (ballBounce == n2)
{
textBox1.Text = number.ToString();
}
break; ...
在这种情况下,循环是无用的。 您可以使用字典。
private Dictinoary<string, string> cases = new Dictionary<string, string> {
{"1", "one"},
{"2", "two"},
// ...
};
// in some method
string text;
if (cases.TryGetValue(ballBounce.ToString(), out text)){
this.textBox1.Text = text;
}
如果您想要比简单值更聪明的东西,可以在字典中使用函数。
private Dictinoary<string, Func<string>> cases = new Dictionary<string, Func<string>> {
{"1", () => "one"},
{"2", () =>
{
if (DateTime.Now.Seconds % 2 == 0) { return "A"; }
else { return "B"; }
}},
// ...
};
// in some method
Func<string> textProvider;
if (cases.TryGetValue(ballBounce.ToString(), out textProvider)){
this.textBox1.Text = textProvider();
}
基于您的ToString(),我假设ballBounce是一个int。
if (ballBounce <= 48 && ballBounce > 0)
{
textBox1.Text = ballBounce.ToString();
}
为什么使用if
with case
? 您无需检查两次。 如果这是每种情况的代码
textBox1.Text = number.ToString();
那么您不需要switch
或者if
jsut编写textBox1.Text = number.ToString();
而且你很好。 另外,如果您遇到某些情况,也可以这样:
switch (ballBounce.ToString())
{
case "1":
case "2":
case"3":
//....
textBox1.Text = number.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.