So I started with no knowledge on reflection or dynamic typing, but I’ve learned a lot. However, there is one thing I cannot find: the “as” equivalent for dynamic typing.
What I’m trying to do is the equivalent of this (if it would compile):
foreach (Change c in changes)
{
(c.Undo as Action<c._Type, c._Type>).Invoke(
c.OldValue as c._Type, c.NewValue as c._Type);
}
From what I understand, I need to do something along the lines of
Type constructedClass = typeof(Action<,>).MakeGenericType(c._Type);
to construct the needed Action class, but is there a way to implement as for both the Action type and c._Type?
For further clarification, here is the pseudocode (and this is my first time trying to do this kind of thing, so please be nice):
foreach (Object o in objects)
{
(o.SettableMethod as Action<o.TypeOfParameters, o.TypeOfParameters>).Invoke(
o.Parameter1 as TypeOfParameters, o.Parameter2 as TypeOfParameters);
}
Thanks in advance.
The purpose of the generics on the Action (or in general) is to allow you to manage type safety at compile time. If you use reflection, you are doing extra work to not get that benefit. You might as well have the signature of your Undo Action take two objects of type
object, and cast to appropriate types inside the action, if needed.Even more generally, you would be better served by a different design. Why are you calling a method on
Changethat sends properties ofChangeback in? Could you not call Undo without any parameters, and leaveChangeresponsible for knowing what the new and old values are?