7
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;

** 我有 36 个这样的案例陈述,每个案例都针对不同的图片框;如何将它们全部分组到一个案例语句中,以便我的代码更高效**

4

4 回答 4

9

看起来您的案例用于选择图像,然后您始终对图像应用相同的处理。

如何将图像存储在列表或字典中,使用该mole值检索正确的图像,然后处理该图像?

就像是

Dictionary<int, PictureBox> images;
var image = images[mole];
// do stuff to image

如果图像都按顺序编号,则 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];
于 2012-07-02T20:19:45.783 回答
3

不同的switch是 pN 变量。不要将这些对象放在离散变量中,而是创建一个可以索引的数组:

var p = new [] { p01, p02, .... }

然后你的代码看起来像这样:

if (p[mole-1].Image == pmiss.Image && MoleHill.Image == pHill.Image)
{
    molesmissed ++;
}
p[mole-1].Image = MoleHill.Image
于 2012-07-02T20:21:59.887 回答
1

您可以将您的 PictureBoxes 放入列表中,然后按索引访问它们:

List<PictureBox> pbs = new List<PictureBox>();
foreach(Control c in this.Controls) if( c is PictureBox ) pbs.Add( (PictureBox)c );

private void MakeMoleVisible(Int32 mole) {
    pbs[ mole ] = // whatever
}
于 2012-07-02T20:20:25.297 回答
0

试试这个:

        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;
            }
        }
于 2012-07-02T20:27:08.167 回答