2013-05-02 44 views
0

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

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

回答

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

感谢好友列表中的方法,完美的:) – Scott 2013-05-02 08:57:12

+0

也加入到了答案:一个更[雅致但价格昂贵](http://stackoverflow.com/questions/2019417/access-random-item-in-list#2019433)解决方案 – 2013-05-02 08:57:24

+0

是的,将Random变成类变量可能是一个好主意,尤其是如果你正在执行'randomDemo()'方法。 – Zbigniew 2013-05-02 08:59:45

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