我想知道是否可以在 C# 中本地创建标记接口,例如在 foreach 循环中。
考虑我们有应该调用其 HandleInput- 和 Update- 方法的游戏组件。这些方法分别定义在相应的接口 IUpdateable 和 IInputHandler 中。我们当然可以像这样进行常规的 foreach 循环:
foreach (var component in Components)
{
if (component.Enabled)
component.Update(gameTime);
if (component.Litsening)
component.HandleInput(gameTime, InputManager);
}
但是,如果有一种方法可以指定迭代变量的类型是由 IUpdateable 和 IInputHandler 构成的临时标记接口,那将是非常简洁的:
foreach ((IInputHandler, IUpdateable) component in Components)
{
if (component.Enabled)
component.Update(gameTime);
if (component.Litsening)
component.HandleInput(gameTime, InputManager);
}
这可能吗,会更好吗?我个人认为它很优雅。// 谢谢,菲利普·希尔德