samedi 24 octobre 2020

What type of argument should be used to take a method as input?

I want to declare a method that takes another method as argument, so that the caller can write:

myClass.LoadCode(SomeClass.AnyMethod);

Inside the method, I'm directly looking at the method declarations and the IL code of it, so I'm actually only interested in the Method property (of type System.Reflection.MethodInfo) of the passed argument.

I have tried:

public Task LoadCode(Delegate method)
{
    return LoadCode(method, method.Method); // Internal method
}

but that requires that the caller does something like:

compiler.LoadCode(new Func<int, int, bool>(SomeClass.AMethodThatTakesTwoIntsAndReturnsBoolean));

I also tried:

public Task<T> LoadCode<T>(T method)
        where T : Delegate
    {
        return LoadCode(method, method.Method);
    }

to no avail,

compiler.LoadCode<Func<int, int, bool>>(SomeClass.AMethodThatTakesTwoIntsAndReturnsBoolean);

isn't much better either.

How do I declare a method that takes another method (or an untyped delegate) as argument, without having to explicitly specify its type/argument list?





Aucun commentaire:

Enregistrer un commentaire