mardi 21 juillet 2020

C# : Assign generic Multicast-Delegate to Action with different amount of parameters via reflection

So in my class are some delegates all being Action<...> fields. Example:

public Action<int> onDiceRolled;
public Action<Turn, Round> onTurnEnded;

and I want to assign an anonymous function to each of them using reflection.

    GetType().GetFields()
    .Where(field => field.FieldType.ToString().Contains("Action"))
    .ToList()
    .ForEach(field =>
    {
        Type type = field.FieldType; // e.g. Action<Turn, Round>
        if (!type.IsGenericType)
            return;

        Type[] para = type.GetGenericArguments(); // in example cases: {int} or {Turn, Round}
        MethodInfo debugMethod = (new Action(() => Console.WriteLine(field.Name + " was called."))).Method;
        field.SetValue(this, Delegate.CreateDelegate(type, debugMethod));
    });

Of course this does not work since the created delegate does not have any parameter while the parameters it needs are stored in para. Unfortunately I cannot find any way to create a delegate by an array of types.

So basically I want to do

onDiceRolled += (i) => Console.WriteLine("onDiceRolled was called.");

for each action field in my class





Aucun commentaire:

Enregistrer un commentaire