1

我目前正在处理一些有效的代码。真的归结为我是否应该让所有这些?盲目的?演员表。

我有一堂课:

public abstract class Trigger
{
  // no logic, just three automatic properties
}

继承自:

// there are several classes like this that store different things like strings,
// int,floats, enums, etc,etc.
public class ActivateOnTimeDelay : Trigger
{
   // More automatic properties and possibly fields.
}

然后我将这些类放入List<Trigger>

并在另一个类中以反向 for 循环遍历列表

if (currentMission.ActiveTriggers.Count > 0)
{
  for (int i = currentMission.ActiveTriggers.Count - 1; i >= 0; i--)
  {
   ActivateOnDeathDelay activateOnDeathD = currentMission.ActiveTriggers[i] as    ActivateOnDeathDelay;
   ActivateOnDeathImmediate activateOnDeathI = currentMission.ActiveTriggers[i] as ActivateOnDeathImmediate;
   ActivateOnFinishDelay activateOnFinishD = currentMission.ActiveTriggers[i] as ActivateOnFinishDelay;
   ActivateOnFinishImmediate activateOnFinishI = currentMission.ActiveTriggers[i] as ActivateOnFinishImmediate;
   ActivateOnFinishMass activateOnFinishM = currentMission.ActiveTriggers[i] as ActivateOnFinishMass;
   ActivateOnTimeDelay activateOnTimeD = currentMission.ActiveTriggers[i] as ActivateOnTimeDelay;
   ActivateOnTimeImmediate activateOnTimeI = currentMission.ActiveTriggers[i] as ActivateOnTimeImmediate;

   DisplayDialog displayDialog = currentMission.ActiveTriggers[i] as DisplayDialog;
   SpawnEnemy spawnEnemy = currentMission.ActiveTriggers[i] as SpawnEnemy;

   if (activateOnDeathD != null)
   {
     // do logic
   }

   // more null checks for each possible item that may be created this loop pass.

当一个触发器被使用时,它会从列表中移除,并且它的 ID 被放置到一个HashSet<string>UsedTriggers 中,一些触发器会监视它。

4

1 回答 1

3

一般来说,这里应该发生的是Trigger(或者可能是一个ITrigger接口)公开了每种具体类型的触发器适当地实现的抽象方法。这样你就不需要投射,你只需做类似的事情

for (int i = currentMission.ActiveTriggers.Count - 1; i >= 0; i--)
{
    // Run() is an abstract method on Trigger
    currentMission.ActiveTriggers[i].Run();
}

或者,使用 LINQ 可能会更好(提高可读性):

foreach (var trigger in currentMission.ActiveTriggers.Reverse())
{
    trigger.Run();
}
于 2013-02-24T16:41:32.360 回答