简体   繁体   English

传递方法或功能作为参数

[英]Passing method or function as parameter

I have an abstract class for Lua scripts. 我有一个Lua脚本的抽象类。 I have a method called Expose which registers a function to the Lua environment. 我有一个称为Expose的方法,该方法向Lua环境注册了一个函数。

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? 因此,除了传递MethodBase之外,我还需要传递什么? 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 ): 您需要两个方法,一个方法接受一个Action委托(一个void方法),另一个方法接受一个Func<T>委托(一个返回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基因重载,每个重载都具有单独的委托类型:

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);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM