如何从List< action>中选择随机元素. [英] How to select a random element from List<action>

查看:76
本文介绍了如何从List< action>中选择随机元素.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法列表,我想从列表中选择一个随机方法并在将布尔值设置为true时执行它.我有:

I have a list of methods, and I want to select a random method from the list and execute it while a boolean is set to true. I have:

 List<Action> myActions = new List<Action>();

 public void SetupRobot()
 {               
    myActions.Add(mRobot.turnLeft);
    myActions.Add(mRobot.turnRight);
    myActions.Add(mRobot.move);
 }


 private void randomDemo()
    {
        while (mRandomActive)
        {           
                foreach (Action aAction in myActions)
                {
                    //randomly method and execute
                    Random rndm = new Random();
                }
        }
    }

不确定如何从对象rndm的列表中选择方法

Unsure as to how I would select the method from the list with object rndm

推荐答案

private void randomDemo()
{
    Random r = new Random();
    while (mRandomActive)
    {           
        int index = r.Next(myActions.Count);
        var action = myActions[index];
        action();
    }
}

这篇关于如何从List&lt; action&gt;中选择随机元素.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆