【问题标题】:How to select a random element from List<action>如何从 List<action> 中选择一个随机元素
【发布时间】:2013-04-26 09:04:59
【问题描述】:

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

【问题讨论】:

    标签: c# list random action


    【解决方案1】:
    private void randomDemo()
    {
        Random r = new Random();
        while (mRandomActive)
        {           
            int index = r.Next(myActions.Count);
            var action = myActions[index];
            action();
        }
    }
    

    【讨论】:

    • 还添加到答案:更多elegant but expensive 解决方案
    • 是的,将Random 转换为类变量可能是个好主意,尤其是在您继续执行randomDemo() 方法时。
    【解决方案2】:
    Random rndm = new Random();    
    while (mRandomActive){
        //randomly method and execute
        var index = rndm.Next(myActions.Count);
        myActions[index]();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-07-23
      • 2010-09-12
      相关资源
      最近更新 更多