I am working on a function of an indie game, which used to take in Action<List<Character>> as a parameter to display the Characters' info. Now I have decided that players can mod the game, so the display system can display anything else than just Characters.
I've overloaded the new display function, which now takes in Action<List<object>> as a parameter. The old function is still being used by the "Character" specific displays, and it would just pass Action<List<Character>> to the new overloaded one, but I have no idea how to cast Action<List<Character>> to Action<List<object>>.
Any help would be appreciated. I'm aware there is an alternative, which is to change all my old Action<List<Character>> to Action<List<object>>, and then cast List<object> to List<Character>.
Asked
Active
Viewed 91 times
1
Li-Qing
- 11
- 2
1 Answers
0
Unfortunately you can't cast it per se, but you can rewrite your original display function that takes an Action<List<Character>> to remap it to the "real" function that takes the Action<List<object>>:
[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
}
Peter Moore
- 1,122
- 10
- 16
>` to `Action
– Johnathan Barclay May 19 '21 at 10:26>`_" - You can't. Nothing to do with `Action` though, it's because `List` is invariant.
>)(list => actionOnListOfCharacters(list.Cast().ToList())`
– Klaus Gütter May 19 '21 at 10:27