I have an abstract class for Lua scripts. I have a method called Expose
which registers a function to the Lua environment.
protected void Expose(string name, MethodBase method)
{
this.Lua.RegisterFunction(name, this, method);
}
However, I want to make it easier by passing the method name only instead of doing this:
this.Expose(this.GetType().GetMethod(...
I want to be able to do this:
this.Expose(LuaExports.DoSomething);
So instead of passing MethodBase, what do I need to pass? Note that the passed argument can be a method that returns something, or a method that does not return anything.
You need two methods, one that accepts an Action
delegate (a void method) and the other that accepts a Func<T>
delegate (a method that returns T
):
protected void Expose(string name, Action method)
{
method(); // will invoke the method passed.
}
protected void Expose(string name, Func<SomeType> method)
{
var value = method(); // will invoke the method passed and assign return result to value.
}
The closest I believe you can come is passing a delegate type directly:
protected void Expose(string name, Delegate delegate)
{
this.Lua.RegisterFunction(name, d.Target, d.Method);
}
Although to be able to call this, you would have to create a delegate type, which can be done with a cast:
this.Expose("Name", (Action)LuaExports.DoSomething);
If you don't want to have the cast you would have to write a whole bunch of genetic overloads of Expose that each take a separate delegate type:
Expose(string name, Action action);
Expose<T1>(string name, Action<T1> action);
Expose<T1, T2>(string name, Action<T1, T2> action);
...
Expose<T1, TResult>>(string name, Func<T1, TResult> action);
Expose<T1, T2, TResult>>(string name, Action<T1, T2, TResult>> action);
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.