How to select a random element from List<action>

时光毁灭记忆、已成空白 提交于 2019-12-25 04:14:52

问题


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();
                }
        }
    }

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


回答1:


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



回答2:


Random rndm = new Random();    
while (mRandomActive){
    //randomly method and execute
    var index = rndm.Next(myActions.Count);
    myActions[index]();
}


来源:https://stackoverflow.com/questions/16333861/how-to-select-a-random-element-from-listaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!