c# - 使用列表的 ASP.Net 随机生成器

标签 c# asp.net random

我正在尝试使用后面的代码中的列表来编写随机生成器。我可以使用下面的代码获得一个完全工作的数字生成器,但我现在希望生成器运行一系列位置而不是数字,但我坚持使用它,因为我对开发完全陌生。

随机数生成器代码

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); 将生成 0Eat.Count - 1 范围内的随机数。 这将在您的列表中生成一个有效的索引。然后 Eat[Places] 访问 随机选择的字符串。

关于c# - 使用列表的 ASP.Net 随机生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125354/

相关文章:

asp.net - ASP.NET 中的线程、TPL 与异步委托(delegate)

java - 从 SecureRandom 获取确定性值?

c# - 如何在 C# 中从 StreamReader 获取文本

javascript - JS函数不在表单内部调用

c# - 如何为 <asp :button>? 的访问 key 添加下划线

java - 如何让java的随机生成器在构造函数语句中生成 double for变量?

c++ - C++中如何让类的成员函数每次调用时生成不同的随机数?

c# - 适用于 ASP.NET MVC 的 Lync Server 聊天客户端 API

c# - Web 服务和 nunit 测试

c# - 选择列表中的所有对象