0

我做了一个简单的数字生成器,我有一个问题:生成器是否可以弹出“红色”、“蓝色”、“绿色”、“黄色”和“白色”而不是数字 1-5?

namespace zufallsgenerator
{
    public partial class Form1 : Form
    {
        Random r = new Random();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnWhlie_Click(object sender, EventArgs e)
        {
            int summe = 0, z; 

            lblAnzeige.Text = " ";

           while (summe <= 0)
           {
                z = r.Next(1, 6);
                summe = summe + z;
           }
           lblAnzeige.Text += summe + "\n";               
        }
    }
}
4

6 回答 6

11

您可以创建一个简单的数组并使用随机生成的索引访问它,例如:

var r = new Random();
string[] colors = {"red", "blue", "green", "yellow", "white"};
var random_color = colors[r.Next(colors.Length)];
于 2013-10-22T14:36:29.133 回答
3

您可以使用enum

定义类似的东西

enum Color
{
   Red,
   Green,
   Blue
}

然后你可以将你的 int 转换为:

Color color = (Color)r.Next(1, 6)

而且,如果你愿意

Text = color.ToString();
于 2013-10-22T14:37:12.837 回答
2

If you get output like 1-5 you could create string[] containing 5 elements

string[] colors = new string[] { "red", "blue", "green", " yellow", "white" }

And instead of retrieving r.Next( 1, 6 ) you could retrieve colors[ r.Next( 0, 5 ) ] (because string array is 0-indexed, changed the min and max value).

于 2013-10-22T14:36:06.607 回答
1

以西欢的回答,你可以使用扩展方法让它更漂亮一点:

public static T Next<T>(this System.Random Random, params T[] List)
{
    if(List.Length==0)
        return default(T);
    return List[Random.Next(0, List.Length)];
}

然后调用它只是:

var r=new System.Random();
var randon_color = r.Next("red", "blue", "green", "yellow", "white");
于 2013-10-22T14:48:25.837 回答
0

What I would do is create a list of strings. Then put the random number as i. So like List<string> list1 = new List<string>{"red", "blue", "green"}; then use your random number like this to call a random element of it. list1[randomNumber];

于 2013-10-22T14:35:59.907 回答
0

Define an array with the posible desired output values and instead of concatenating summe to text, add YourArrayOfNamedValues[summe]

于 2013-10-22T14:36:01.297 回答