mercredi 26 août 2020

Pass a Func

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.





Aucun commentaire:

Enregistrer un commentaire