问题
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