我目前正在处理一些有效的代码。真的归结为我是否应该制作所有这些?盲目?管型。
我有一个班级:
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>
并且在另一个类中以反向循环遍历列表
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中。
答案 0 :(得分: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();
}