如何在C#中将函数作为参数传递? [英] How to pass a function as a parameter in C#?

查看:34
本文介绍了如何在C#中将函数作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C# 中将函数作为参数传递?我可以使用 Func 或 Action 类来完成,但这迫使我一次声明整个函数签名.当我尝试使用 Delegate 时,我收到一个编译错误,指出它无法将方法组转换为 Delegate.

Is it possible to pass a function as a parameter in C#? I can do it using the Func or Action classes, but this forces me to declare the entire function signature at once. When I try to use Delegate, I get a compile error saying it can't convert a method group to a Delegate.

我正在研究 Axial 并且我正在尝试允许用户调用网络服务.我想要的是能够创建 Visual Studio 代理类,然后传入生成的函数.函数签名无关紧要,因为生成的代码仅使用函数名称.但是,我想传入函数而不是名称,原因有两个:能够使用代理的 Url 属性,如果 Web 服务不存在或在 Visual Studio 中更新,则会出现编译器错误.

I'm working on Axial and I'm trying to allow users to call web services. What I'm going for is the ability to create the Visual Studio proxy class and then pass in the generated function. The function signature doesn't matter because the generated code only uses the function name. However, I'd like to pass in the function instead of the name for two reasons: the ability to use the proxy's Url property and a compiler error if the web service doesn't exist or is updated in Visual Studio.


public void AlertIt(object o) {
    Axial.DOM.Window.Alert(o.ToString());
}
public void CallAddService() {
    object[] param = new object[] { int.Parse(txtA.Text), int.Parse(txtB.Text) };
    Axial.ServerScript.CallWebService(new WSProxy.WS().Add, param, AlertIt, AlertIt);
}

class Axial.ServerScript {
    public void CallWebService(Delegate method, object[] param, Action<object> successCallback, Action<object> failureCallback) {
        // translate to javascript (already working)
    }
}

推荐答案

我想你想要的是:

static object InvokeMethod(Delegate method, params object[] args){
    return method.DynamicInvoke(args);
}

static int Add(int a, int b){
    return a + b;
}

static void Test(){
    Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4));
}

打印9".

这篇关于如何在C#中将函数作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆