如何从List <action> </action>中选择一个随机元素

时间:2013-05-02 08:49:33

标签: c# list random action

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

 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

的方法

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

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