Ale*_*son 7 c# case switch-statement
private void makeMoleVisable(int mole, PictureBox MoleHill)
{
switch (mole)
{
case 1:
if (p01.Image == pmiss.Image && MoleHill.Image == pHill.Image)
{
molesmissed ++;
}
p01.Image = MoleHill.Image;
break;
case 2:
if (p02.Image == pmiss.Image && MoleHill.Image == pHill.Image)
{
molesmissed++;
}
p02.Image = MoleHill.Image;
break;
Run Code Online (Sandbox Code Playgroud)
**我有36个这样的案例陈述,每个用于另一个用于不同的图片框; 如何将它们全部分组到一个case语句中,以便我的代码更高效**
看起来您的情况用于选择图像,然后您始终对图像应用相同的处理.
如何将图像存储在列表或字典中,使用该mole值来检索正确的图像,然后处理该图像?
就像是
Dictionary<int, PictureBox> images;
var image = images[mole];
// do stuff to image
Run Code Online (Sandbox Code Playgroud)
如果图像全部按顺序编号,则List略高一些.请记住,列表索引是基于0.如果您从1开始对图像进行编号,就像您的switch陈述中所示(在以下示例中假设),请记住相应地进行调整.
List<PictureBox> images;
int index = mole - 1; // Assumes mole starts with 1, so adjust to 0-based index
var image = images[index];
Run Code Online (Sandbox Code Playgroud)
尝试这个:
string ControlIdSuffix = mole < 10 ? "0" : "" + mole.ToString();
Control[] picBoxes = this.Controls.Find("p" + ControlIdSuffix, true);
if (picBoxes.Length > 0)
{
PictureBox p = picBoxes[0] as PictureBox;
if (p != null) {
if (p.Image == pmiss.Image && MoleHill.Image == pHill.Image)
molesMissed++;
p.Image = MoleHill.Image;
}
}
Run Code Online (Sandbox Code Playgroud)