如何使用循环? [英] How to use loop for ?

查看:127
本文介绍了如何使用循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有例子;

i have example;

 if (a == "8")
    comboBox3.SelectedIndex = 0;

if (a == "9")
    comboBox3.SelectedIndex = 1;
if (a == "10")
    comboBox3.SelectedIndex = 2;

if (a == "11")
    comboBox3.SelectedIndex = 3;
if (a == "12")



我尝试过的事情:

我想使用循环,使代码简短,每个人都可以帮助我,谢谢



What I have tried:

I want to use loop for, make this code short, everyone can help me, thanks

推荐答案

首先:不要使用
First of all: Don''t use Magic numbers - Wikipedia[^]

A for loop won''t help. What you have there is a mapping: You map "8" to 0, "9" to 1 etc. And a map in C# is a dictionary. I''m not sure what you''re trying to do there couldn''t be done in a completely different and better way but with a dictionary it would look like this:

// create the dictionary at some central place so that it
// only needs to be created once:
Dictionary<string, int> SelectedIndexMapping = new Dictionary<string, int>()
{
   { "8", 0 },
   { "9", 1 },
   // etc
};


// and then somewhere else instead of your shown code:
comboBox3.SelectedIndex = SelectedIndexMapping[a];

// or, if the string a could contain an invalid value:
int index;
if (SelectedIndexMapping.TryGetValue(a, out index))
   comboBox3.SelectedIndex = index;
else
   // show an error-message or set comboBox3.SelectedIndex to some default value 



同样,只是发生在我身上,如果索引始终比a中的数字小8,则可以将a中的值解析为整数,而不是字典,然后将其减去8并将结果分配给comboBox3.SelectedIndex :



Also, just occurred to me, if the index is always smaller by 8 than the number in a then instead of the dictionary you could parse the value in a into an integer, subtract 8 and assign the result to comboBox3.SelectedIndex:

int index;
if (Int32.TryParse(a, out index))
    comboBox3.SelectedIndex = index - 8;
else
    // show an error-message or set comboBox3.SelectedIndex to some default 



在第二个代码示例中,使用TryParse(..)修复了脑部屁屁



fixed a brain fart with TryParse(..) in the second code example


这篇关于如何使用循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆