我正在尝试使用后面的代码中的列表来编写随机生成器.我能够使用下面的代码获得一个完全正常工作的数字生成器,但我现在希望生成器运行一个地方列表而不是数字,但我坚持使用它,因为我完全不熟悉开发.
随机数生成器的代码
private void btnGenerate_Click(object sender, EventArgs e)
{
Random Place = new Random();
int Places = Place.Next();
txtResult.Text = Places.ToString();
}
Run Code Online (Sandbox Code Playgroud)
正如我所说,我希望我的发电机使用吃饭的地方(例如),但我被卡住了
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();
}
Run Code Online (Sandbox Code Playgroud)
我累了注释int Places = Place.Next();并更改txtResult.Text = Places.ToString();为txtResult.Text = Eat.ToString();但是当我点击'Generate'按钮时,这会导致我的应用程序字段中显示以下错误
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];
Run Code Online (Sandbox Code Playgroud)
线int Places = Place.Next(0, Eat.Count);
将产生的范围内的随机数0到Eat.Count - 1.这将在列表中生成有效索引.然后Eat[Places]访问randoly选择的字符串.