我正在尝试使用后面的代码中的列表来编写随机生成器。我可以使用下面的代码获得一个完全工作的数字生成器,但我现在希望生成器运行一系列位置而不是数字,但我坚持使用它,因为我对开发完全陌生。
随机数生成器代码
private void btnGenerate_Click(object sender, EventArgs e)
{
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
正如我所说,我希望我的发电机能够使用吃饭的地方(例如),但我被困住了
private void btnGenerate_Click(object sender, EventArgs e)
{
Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
我厌倦了注释 int Places = Place.Next();
并将 txtResult.Text = Places.ToString();
更改为 txtResult.Text = Eat.ToString();
但这会导致当我单击“生成”按钮时在我的应用程序的字段中显示以下错误
System.Collections.Generic.List`1[System.String]
最佳答案
试试这个:
List<string> Eat = new List<string>();
Eat.Add("Tesco");
Eat.Add("KFC");
Eat.Add("Subway");
Eat.Add("Chippy");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtResult.Text = Eat[Places];
行int Places = Place.Next(0, Eat.Count);
将生成 0
到 Eat.Count - 1
范围内的随机数。
这将在您的列表中生成一个有效的索引。然后 Eat[Places]
访问
随机选择的字符串。
关于c# - 使用列表的 ASP.Net 随机生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125354/