Pass a Func<T,bool> as a parameter using reflection?

littlecharva

I have a method:

public bool DoStuff<T>(T obj) {
  // Do Stuff
  return result;
}

And I need to pass that as a Func<T, bool> parameter to another method that I don't know at compile time. Let's say that method looks like:

public int Any(Func<int, bool> arg) {
}

Or

public int Any(Func<string, bool> arg) {
}

So I'm invoking that method like this:

return instance.GetType().InvokeMember(method.Name, BindingFlags.InvokeMethod, null, instance, args);

What I can't figure out is how to wrap up a reference to DoStuff as a Func<T,bool>, where I don't know T at compile time, but DO know it at runtime, and stuff it into an object[] to provide as the parameters to the method call.

If it helps, I'm writing an interpreter of a simple language. DoStuff will interpret a lambda expression in the simple language and the invoked methods will be .NET functions provided by the consumer of the interpreter.

Update

After following the link provided in the comments by Hans (thanks!) I've implemented the following:

Type delegateType = typeof(Func<,>).MakeGenericType(new []{argType, typeof(bool)});
MethodInfo delegatedMethod = this.GetType().GetMethod(nameof(DoStuff), BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
MethodInfo generic = delegatedMethod.MakeGenericMethod(argType);

Delegate myDelegate = Delegate.CreateDelegate(delegateType, this, generic);
var args = new object[] { myDelegate };

return instance.GetType().InvokeMember(method.Name, BindingFlags.InvokeMethod, null, instance, args);

But the InvokeMember call gives me System.MissingMethodException: 'Method 'MyDomain.Any' not found.'

When I inspect the myDelegate variable in Visual Studio it shows:

myDelegate = {Method = {Boolean DoStuff[Func`2](System.Func`2[System.Int32,System.Boolean])} 

It's the ONLY element in the args array, and the method signature I'm invoking is:

public int Any(Func<int, bool> arg)

instance is an instance of the class containing the Any method, and method is a MethodInfo for the Any method.

Lause

So here's some code that works:

public class AnyImplementer
{
   public int Any(Func<int, bool> func)
    {
        return func(10)? 1: 0;
    }

  
}

public class DoStuffer
{
    public bool DoStuff<T>(T obj)
    {
        return obj.ToString() != string.Empty;
    }

    public int a(Type argType, AnyImplementer anyImplementer)
    {
        Type delegateType = typeof(Func<,>).MakeGenericType(new[] { argType, typeof(bool) });
        MethodInfo delegatedMethod = this.GetType().GetMethod(nameof(DoStuff), BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance);
        MethodInfo generic = delegatedMethod.MakeGenericMethod(argType);

        Delegate myDelegate = Delegate.CreateDelegate(delegateType, this, generic);
        var args = new object[] { myDelegate };

        return (int)anyImplementer.GetType().InvokeMember("Any", BindingFlags.InvokeMethod, null, anyImplementer, args);
    }
}


public class Program
{
   
    public static void Main(string[] args)
    {
        DoStuffer DoStuffer = new DoStuffer();
        AnyImplementer anyImplementer = new AnyImplementer();
       Console.WriteLine(DoStuffer.a(typeof(int), anyImplementer));
       
    }

    
}

Also accessible at https://pastebin.com/raw/3UxN6Sn4 - The idea is (as based on OP's updates and related questions) to create wrap the method instance into an object using a delegate constructed out of the method info of the generic method group.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Identify Func<> parameter in method using reflection

How pass Func<T> to method parameter

How can I get the return type of a Func<T> using reflection?

How to invoke with reflection a method that accepts a Func<> parameter?

Pass parameter to function via reflection

IMongoCollection<T> throws an when I pass in a predicate for Func<T, bool>

Use Func<T,bool>[] as a parameter list and check the result for each function

Func<T> with out parameter

How to set a parameter while using Expression<Func<T>>

Using a Func expression as a parameter in GroupBy

pg-promise: Pass a function as parameter to func()

How to pass "type" as input parameter to func in Postgresql

C# Get Method by reflection with Expression<Func<TEntity,object>> in Parameter

Can't pass a parameter to $_POST using the XMLHttpRequest

Func<T, TResult> access parameter

Invoke a Func object using reflection and a Type that's known at runtime

C# extension using function Func as parameter

Using delegate func as method parameter error

Reflection MemberInfo to Func<T1, T2>

Convert values based on parameter type using reflection

Invoke method with an array parameter using reflection

Get parameter of a class constructor using reflection

Comparing generic parameter type using reflection

Call a function with default parameter values using reflection

Pass nested class to constructor using reflection

How to pass an argument by reference using Reflection

Why can't I pass a `func() []int` as `func() []interface{}` in go?

How to pass values to a variadic parameter in a func from a variadic arguement

How to pass func with any return type as parameter into another function?