如何使代码比case场景更高效

本文关键字:高效 case 何使 代码 | 更新日期: 2023-09-27 18:10:13

我正在编写一个简单的水果机,这是我的方法之一,我想知道是否有可能使这段代码更有效:(在使用案例之前,我有一个if/else if语句)

_intNudgeCount获取一个介于0 - 9之间的数字。

public void DrawNudgeCount()
    {
        switch (_intNudgeCount)
        {
            case 9:
                pictureBoxNudgeCount.Image = Properties.Resources._9;
                break;
            case 8:
                pictureBoxNudgeCount.Image = Properties.Resources._8;
                break;
            case 7:
                pictureBoxNudgeCount.Image = Properties.Resources._7;
                break;
            case 6:
                pictureBoxNudgeCount.Image = Properties.Resources._6;
                break;
            case 5:
                pictureBoxNudgeCount.Image = Properties.Resources._5;
                break;
            case 4:
                pictureBoxNudgeCount.Image = Properties.Resources._4;
                break;
            case 3:
                pictureBoxNudgeCount.Image = Properties.Resources._3;
                break;
            case 2:
                pictureBoxNudgeCount.Image = Properties.Resources._2;
                break;
            case 1:
                pictureBoxNudgeCount.Image = Properties.Resources._1;
                break;
            case 0:
                pictureBoxNudgeCount.Image = Properties.Resources._0;
                break;
        }
    }

提前感谢!

解决:

没关系,我已经把它压缩到3行代码:

//在类的顶部声明资源图像

private System.Drawing.Image[]  _arrayNudgeCount;

//在加载类时填充数组

_arrayNudgeCount = new System.Drawing.Image[] { Properties.Resources._0, Properties.Resources._1};

//重新绘制图像
public void DrawNudgeCount()
{
pictureBoxNudgeCount.Image = _arrayNudgeCount[_intNudgeCount];
}

如何使代码比case场景更高效

如果我是你,我会把它简化成一行代码!

pictureBoxNudgeCount.Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + _intNudgeCount);

将您的图像放在应用程序旁边的文件夹中,并调用pictureBoxNudgeCount.Load(ConstantSectionPath+_intNudgeCount+".jpg");如果你的文件扩展名是JPG