[英]How do I get a random item from a ListBox, then compare it in C#?
Currently, I have this: 目前,我有这个:
Random random = new
random.Next(1, strings.Items.Count);
strings.Select();
strings.SelectedItem = strings.Items[Convert.ToInt32(random)];
var str = strings.SelectedItem;
if (str == "stuff")
{
//Here
}
It doens't give any errors in the output, but it won't run when I test it. 它不会在输出中给出任何错误,但在测试时它不会运行。 I get an InvalidCastException
, saying it was unable to cast an object of type System.Random
to the type System.IConvertible
. 我得到一个InvalidCastException
,说它无法将System.Random
类型的对象InvalidCastException
为System.IConvertible
类型。
What does this error mean, and how can I fix it? 这个错误意味着什么,我该如何解决?
Your original code shouldn't compile (You missed new Random();
on the first line). 您的原始代码不应该编译(您错过了new Random();
在第一行)。 It should be: 它应该是:
Random random = new Random();
int randomNumber = random.Next(1, strings.Items.Count);
strings.Select();
strings.SelectedItem = strings.Items[randomNumber];
var str = strings.SelectedItem;
if (str == "stuff")
{
//Here
}
You are getting the exception on following line, which tries to convert random
object to the int, that you can't do and that is why you are getting the exception. 您正在获取以下行的异常,该行尝试将random
对象转换为int,您无法执行此操作,这就是您获得异常的原因。
strings.Items[Convert.ToInt32(random)]
It is wrong to index the string.Items
based on the random
object. 索引string.Items
基于random
对象的错误。 It should be the random number returned by the random
object, not the object itself. 它应该是random
对象返回的随机数,而不是对象本身。
Change the code to following: 将代码更改为以下内容:
Random random = new
int rnd = random.Next(1, strings.Items.Count);
strings.Select();
strings.SelectedItem = strings.Items[rnd];
var str = strings.SelectedItem;
if (str == "stuff")
{
//Here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.