【问题标题】:generate method calls c# using a loop [duplicate]使用循环生成方法调用c#[重复]
【发布时间】:2016-07-19 18:18:56
【问题描述】:

我正在使用 Visual Studio Community 2015 制作一个基于表单的程序,该程序可以掷两个骰子。我需要根据我得到的随机数更改图片。

我可以这样做的方法是:

Random num = new Random();
int dice = num.Next(1,7);

if (dice == 1)     {
  pictureBox.Image = proj08.Properties.Resources._1;
} else if (dice == 2)    {
  pictureBox.Image = proj08.Properties.Resources._2;
} else if (dice == 3)    {
  pictureBox.Image = proj08.Properties.Resources._3;
} else if (dice == 4)    {
  pictureBox.Image = proj08.Properties.Resources._4;
} else if (dice == 5)    {
  pictureBox.Image = proj08.Properties.Resources._5;
} else if (dice == 6)    {
  pictureBox.Image = proj08.Properties.Resources._6;    }

这完美地工作并且做我想要的,但它是非常混乱的代码。我想通过执行以下操作来清理它:

Random num = new Random();
int dice = num.Next(1,7);
pictureBox.Image = proj08.Properties.Resources._dice;

但这不起作用。 我也想使用相同的代码,即使图片框是图片框1或图片框2,这样我就可以将它用于任何一个骰子。

【问题讨论】:

标签: c#


【解决方案1】:

你可以有一张图片列表:

List<Image> images = new List<Image>()
{
   proj08.Properties.Resources._1,
   proj08.Properties.Resources._2,
   proj08.Properties.Resources._3,
   proj08.Properties.Resources._4,
   proj08.Properties.Resources._5,
   proj08.Properties.Resources._6
};

Random num = new Random();
int dice = num.Next(1, images.Count + 1);
pictureBox.Image = images[dice - 1]; // list starts from 0

这是我能想到的最直接优雅的方式。

对于多个图片框,您可以创建一个将图片框作为参数传递的方法,并在其中设置其图像属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2020-02-27
    • 2020-06-10
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    • 2016-01-25
    相关资源
    最近更新 更多