vendredi 16 octobre 2020

C# Create lambda over given method that injects first paramater [duplicate]

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

Is there any way I can create such wrapper automatically (or semi-automatically)?

Update

There is dedicated abstract method void RegisterAll(ScriptEngine script) that can register required members of given subclass

Update2

Example of what I am trying to achieve (requested in comment)

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) {
        script.RegisterApi(nameof(MyMethod), (Delegate)Wrap<string>(MyMethod, script)); // Is there any way to shorten this up (not providing MyMethod twice, not providing template arguments?)
    }

}




Aucun commentaire:

Enregistrer un commentaire