PMF
PMF

Reputation: 17328

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?

Upvotes: 0

Views: 33

Answers (1)

Yehor Androsov
Yehor Androsov

Reputation: 6152

Just a workaround with the use of strings

using System;
using System.Linq;

namespace ConsoleApp14
{
    class Program
    {
        static void Main(string[] args)
        {
            LoadCode(typeof(SomeClass), nameof(SomeClass.SomeMethod));
        }

        static void LoadCode(Type type, string methodName)
        {
            var methods = type.GetMethods().Where(x => x.Name == methodName).ToList();
            if (methods.Count == 0) 
            {
                // not a method
            }
        }
    }

    public class SomeClass
    {
        public void SomeMethod()
        {

        }
        public void SomeMethod(object o)
        {

        }
    }
}

Upvotes: 1

Related Questions