如何从列表中选择随机字符串并将其分配给变量C#

时间:2015-11-11 02:19:02

标签: c# .net list random

我正在尝试创建一个用户输入字符串的程序,然后将该字符串存储在名为word1的List中。我想从List中选择一个随机字符串,并将其显示在标签中。我尝试使用多种方法和类作为练习来做到这一点。这是我的代码:

这是Class1.cs类:

    main main = new main();

    public string flashCards1()
    {
        List<string> word1 = main.GetList1();

        Random rnd = new Random();

        int rtn = rnd.Next(word1.Count - 1);

        string word = word1[rtn];

        string rtnWord = word.ToString();

        return rtnWord;
    }

这个是在main.cs(不是Main)中,它与Class1对话。就像我说的那样,这部分可能是不必要的,但我试图用多种方法练习。

    private List<string> word2 = new List<string>();
    private List<string> word1 = new List<string>();

    public List<string> GetList1()
    {
        return word1;
    }

    public void SetList1(List<string> updatedList)
    {
        word1 = updatedList;
    }

这个在Form1.cs中,并将标签设置为flashCards1的返回值:

    private void go_Click(object sender, EventArgs e)
    {
        menu.Visible = false;
        cards.Visible = true;

        label1.Text = class1.flashCards1();

    }

这也在Form1.cs中并将文本保存到List:

    private void enter_Click(object sender, EventArgs e)
    {
        List<string> word1 = main.GetList1();

        word1.Add(textBox1.Text);

        main.SetList1(word1);
    }

当我运行此代码时,它会出现错误:

  

System.ArgumentOutOfRangeException未处理     的HResult = -2146233086     消息=&#39;包括maxValue&#39;必须大于零。   参数名称:maxValue     PARAMNAME等于MAXVALUE     来源= mscorlib程序     堆栈跟踪:          在System.Random.Next(Int32 maxValue)          位于C:\ Users \ lottes \ Source \ Workspaces \ Workspace \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Class1.cs中的WindowsFormsApplication1.Class1.flashCards1():第19行          at WindowsFormsApplication1.Form1.go_Click(Object sender,EventArgs e)位于C:\ Users \ lottes \ Source \ Workspaces \ Workspace \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Form1.cs:第62行          在System.Windows.Forms.Control.OnClick(EventArgs e)          在System.Windows.Forms.Button.OnClick(EventArgs e)          在System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)          在System.Windows.Forms.Control.WmMouseUp(消息&amp; m,MouseButtons按钮,Int32点击)          在System.Windows.Forms.Control.WndProc(消息&amp; m)          在System.Windows.Forms.ButtonBase.WndProc(消息&amp; m)          在System.Windows.Forms.Button.WndProc(消息&amp; m)          在System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)          在System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)          在System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd,Int32 msg,IntPtr wparam,IntPtr lparam)          在System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg)          在System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID,Int32 reason,Int32 pvLoopData)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason,ApplicationContext context)          在System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason,ApplicationContext context)          在System.Windows.Forms.Application.Run(Form mainForm)          at WindowsFormsApplication1.Program.Main()在C:\ Users \ lottes \ Source \ Workspaces \ Workspace \ WindowsFormsApplication1 \ WindowsFormsApplication1 \ Program.cs:第19行          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()     InnerException:

我试图输入很多值,但它似乎不起作用。我也看了这个帖子: How could I get a random string from a list and assign it to a variable

然而他们的解决方案给了我同样的错误。 任何帮助将不胜感激。对不起,如果这是太多/很少的信息。我试图理解。

1 个答案:

答案 0 :(得分:5)

您的问题在于Random.Next(int)方法。当您尝试使用负值作为最大参数时,会出现此异常。这是因为它返回>= 0 and < maxValue之间的值。哪个被负值搞砸了(在你的情况下,当列表有0个项目时为-1)

修复很简单,只需更改:

        int rtn = rnd.Next(word1.Count - 1);

成:

        int rtn = rnd.Next(word1.Count);

这应该有效,因为随机总是返回值小于的最大值,所以应该访问0到N - 1,其中N是列表的大小。

在此之后你会遇到进一步的问题(与此直接问题的关联性较小),但核心问题是你在{ {1}}功能。在您向我们展示的示例中,我们不清楚如何解决这个问题,但我建议您查看函数执行的顺序。