In C# I have following methods defined in given class (non static):
int MyMethod(ScriptEngine script, int a, int b) { return a + b; } void MyMethod2(ScriptEngine script, string c) { // do something with c } I want to create wrapping lambda / Action / Delegate / MethodInfo (all are accepted by script engine) that automatically passes ScriptEngine and this from given, predefined variables.
So far I've experimenting with:
// With overloads up to 16 template parameters Action<T1> Wrap<T1>(Action<ScriptEngine, T1> func, ScriptEngine script) { return (Action<T1>) ((t1) => func(script, t1)); } But when called on MyMethod2 I've got The type arguments for method … cannot be inferred from the usage. Try specifying the type arguments explicitly. If I specify the template arguments explicity, it works, but I want to avoid such specification.
Is there any other way (not neccesery following my solution) I can create such wrapper automatically (or semi-automatically)?
It is worth mentioning that there is a dedicated abstract method void RegisterAll(ScriptEngine script) that can register required members of given subclass.
Here is an example of what I am trying to achieve:
class ScriptEngine { // Stub to have complete example, actual implementation is defined elsewhere void RegisterApi(string name, MethodInfo methodInfo) { } void RegisterApi(string name, Delegate delegateSelf) { } } class Api { int MyMethod(ScriptEngine script, int a, int b) { return a + b; } void MyMethod2(ScriptEngine script, string c) { // do something with c } void RegisterAll(ScriptEngine script) { // Is there any way to shorten this up (not providing MyMethod twice, not providing template arguments?) script.RegisterApi(nameof(MyMethod), (Delegate)Wrap<string>(MyMethod, script)); } } The problem is how to improve this RegisterApi method so it:
- Takes the method only once
- Does not require specifying arguments via template method