[英]C#, how to Cast Action<List<T>> to Action<List<object>>
我正在开发一款独立游戏的 function,它曾经将Action<List<Character>>
作为参数来显示角色的信息。 现在我决定玩家可以修改游戏,因此显示系统可以显示除角色之外的任何其他内容。
我已经重载了新的显示 function,它现在将Action<List<object>>
作为参数。 旧的 function 仍在使用“字符”特定显示器,它只会将Action<List<Character>>
传递给新的重载显示器,但我不知道如何将Action<List<Character>>
转换为Action<List<object>>
。
任何帮助,将不胜感激。 我知道有另一种选择,即将我所有的旧Action<List<Character>>
更改为Action<List<object>>
,然后将List<object>
转换为List<Character>
。
不幸的是,您本身不能投射它,但您可以重写原始显示 function ,它需要一个Action<List<Character>>
将其重新映射到采用Action<List<object>>
的“真实” function :
[Obsolete]
internal void DisplayFunction(Action<List<Character>> charAction)
{
DisplayFunction((objs) =>
{
// I don't know if you need this type safety;
// depends on whether your display function
// might invoke the callback with anything other
// than Character - but I assume it could, otherwise
// why go through this exercise?
charAction(objs.Where(obj=>obj is Character)
.Select(obj=>(Character)obj)
.ToList());
});
}
public void DisplayFunction (Action<List<object>> action)
{
// the real display function
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.