可以在C#中简化此switch和while循环吗?

时间:2018-11-16 10:49:00

标签: c#

while (p3.Alive || p2.Alive)
        {
            Random rnd = new Random();
            int victim = rnd.Next(1, 3);

            switch (victim)
            {
                case 1:
                    p1.Attack(p2, 2);
                    break;
                case 2:
                    p1.Attack(p3, 2);
                    break;
            }

            Thread.Sleep(2000);
        }

p2和p3以及Person类的对象。他们将被凶手p1随机杀死。但是,当我看着它时,我觉得可能会有更好的解决方案,因为如果我准备杀死1000个类Person的对象怎么办?我只是似乎无法让p2和p3成为易于编程的变量。

while循环是相同的。如果我有1000个对象怎么办。甚至只有10个。我该如何写成这样的条件:“除了杀手之外,还有其他人还活着”,以及攻击随机rnd选择的任何人的“如果”或“开关”?

该问题在主题中写得不好。我不知道如何将所有这些总结为一个简短的问题。如果有人有好的建议,我将对其进行编辑。谢谢。

2 个答案:

答案 0 :(得分:3)

这似乎本质上是一次掷硬币,有2个结果。可以使用“条件”运算符对2个结果进行建模:

var target = rnd.Next(0,2) == 0 ? p2 : p3;
pi.Attack(target);

对于较大的组,将可能的目标放在列表或数组中可能会很有用;那么您基本上可以做到:

var target = list[rnd.Next(list.Count)];

或者在C#8中,“开关表达式”可能会有用:

var target = rnd.Next(4) switch (
   case 0: p1,
   case 1: p2,
   case 2: p3,
   case 3: p4,
   case _: default
);

答案 1 :(得分:3)

解决所有问题:

  • 仅创建一个随机对象
  • 使用列表避免重复代码
  • 不要攻击不再活跃的对手
using System.Collections.Generic;             // provides the List type

Random rnd = new Random();
var opponents = new List<Player> { p2, p3 };  // add more as needed

while (true)
{
    opponents.RemoveAll(x => !x.Alive);  // only keep live enemies (efficient: does not create new List)
    if (opponents.Count == 0)            // if nobody left --> exit loop
        break;

    int victim = rnd.Next(0, opponents.Count);
    p1.Attack(opponents[victim]);
    Thread.Sleep(2000);
}