通过反复试验我最后请帮助我。随机生成器,为文本框生成5个随机字母,所有字母必须有自己的随机机会。我正在寻找一种更清晰的方式来编写这个随机字母生成器。也许是使用Random()的另一种方式。
private void GenerateLetter_Click(object sender, EventArgs e)
{ Random rnd = new Random();
String[] rArray = { "A", "B", "C", "D", "E", "F", "G" };
int x1 = rnd.Next(0,7);
int x2 = rnd.Next(0, 7);
int x3 = rnd.Next(0, 7);
int x5 = rnd.Next(0, 7);
int x6 = rnd.Next(0, 7);
int x7 = rnd.Next(0, 7);
int x8 = rnd.Next(0, 7);
int x9 = rnd.Next(0, 7);
int x10 = rnd.Next(0, 7);
int x11 = rnd.Next(0, 7);
int x12 = rnd.Next(0, 7);
int x13 = rnd.Next(0, 7);
int x14 = rnd.Next(0, 7);
int x15 = rnd.Next(0, 7);
int x16 = rnd.Next(0, 7);
int x17 = rnd.Next(0, 7);
int x18 = rnd.Next(0, 7);
int x19 = rnd.Next(0, 7);
int x20 = rnd.Next(0, 7);
textBox1.Text = rArray[x1] + rArray[x2] + rArray[x3] + rArray[x4] + rArray[x5];
textBox2.Text = rArray[x6] + rArray[x7] + rArray[x8] + rArray[x9] + rArray[x10];
textBox3.Text = rArray[x11] + rArray[x12] + rArray[x13] + rArray[x14] + rArray[x15];
textBox4.Text = rArray[x16] + rArray[x17] + rArray[x18] + rArray[x19] + rArray[x20];
}
答案 0 :(得分:3)
static readonly Random Rand = new Random();
private const string Alpha = "ABCDEFG";
public static string GenerateAlphaString(int size)
{
var chars = new char[size];
for (int i = 0; i < size; i++)
{
chars[i] = Alpha[Rand.Next(Alpha.Length)];
}
return new string(chars);
}
然后调用该方法:
textBox1.Text = GenerateAlphaString(5);
答案 1 :(得分:0)
一种给你一个随机字母的静态方法:
using System;
static class RandomLetter
{
static Random _random = new Random();
public static char GetLetter()
{
int num = _random.Next(0, 26); // Zero to 25
char let = (char)('a' + num);
return let;
}
}
使用:
Console.WriteLine(RandomLetter.GetLetter());
答案 2 :(得分:0)
此代码与您提供的代码完全相同:
private static Random rand = new Random();
private static string alphabet = "ABCDEFG";
private static string GetRandomString(int length)
{
var stringBuilder = new StringBuilder();
for (int i = 0; i < length; i++)
{
stringBuilder.Append(alphabet[rand.Next(0, alphabet.length)]);
}
return stringBuilder.ToString();
}
private void GenerateLetter_Click(object sender, EventArgs e)
{
textBox1.Text = GetRandomString(5);
textBox2.Text = GetRandomString(5);
textBox3.Text = GetRandomString(5);
textBox4.Text = GetRandomString(5);
}