0

我有一个方法列表,我想从列表中选择一个随机方法并在布尔值设置为 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 从列表中选择方法

4

2 回答 2

3
private void randomDemo()
{
    Random r = new Random();
    while (mRandomActive)
    {           
        int index = r.Next(myActions.Count);
        var action = myActions[index];
        action();
    }
}
于 2013-05-02T08:52:32.103 回答
1
Random rndm = new Random();    
while (mRandomActive){
    //randomly method and execute
    var index = rndm.Next(myActions.Count);
    myActions[index]();
}
于 2013-05-02T08:54:09.190 回答