假设我有一个IEnumerator
的列表:
public List<IEnumerator> routines;
假设我有这个枚举:
public enum Shape { CIRCLE, TRIANGLE, SQUARE }
[我有很多IEnumerator
例程都将Shape
作为参数:
public IEnumerator Move(Shape shape, float distance){ /* code */ }
public IEnumerator Jump(Shape shape, float height){ /* code */ }
public IEnumerator Fire(Shape shape, float power){ /* code */ }
我的列表routines
将包含这些功能的一系列实例(稍后将在StartCoroutine
中调用:]
routines.Add(Move(Shape.SQUARE, 1));
routines.Add(Jump(Shape.CIRCLE, 1));
routines.Add(Fire(Shape.TRIANGLE, 1));
//...
鉴于我已经用所有这些函数填充了routines
,是否有办法让我遍历routines
并找出每个函数调用的Shape
参数?在这种情况下,它将是SQUARE,CIRCLE,TRIANGLE等。
如果您的枚举器实现了解“形状”,则可以从routines
中投射项目并获得形状。
public interface IShapedEnumerator : IEnumerator {
Shape EnumeratorShape {get; }
}
pblic class ShapedIteratorProxy : IShapedEnumerator {
private readonly IEnumerator _baseEnumerator;
private readonly Shape _shape;
public Shape EnumeratorShape => _shape;
public ShapedIteratorProxy (Shape shape, IEnumerator baseEnumerator) {
_baseEnumerator = baseEnumerator;
_shape = shape;
}
public ShapedIteratorProxy (Shape shape, float arg, Func<Shape, float, IEnumerator> operation)
: this(shape, operation(shape, arg))
{}
// implementation of IEnumerator that proxy all calls to _baseEnumerator.
// ...
}
routines.Add(new ShapedIteratorProxy(Shape.SQUARE, Move(Shape.SQUARE, 1)));
routines.Add(new ShapedIteratorProxy(Shape.CIRCLE, 1, Jump);
routines.Add(new ShapedIteratorProxy(Shape.TRIANGLE, 1, Fire);
var shapes = routines.OfType<IShapedEnumerator>()
.Select(s=>s.EnumeratorShape)
.ToArray();
请注意,如果routines
包含未实现IShapedEnumerator
的项目,则将跳过它们。