如何通过一个函数在C#中的参数? [英] How to pass a function as a parameter in C#?

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

问题描述

是否有可能通过一个函数在C#中的参数?我可以使用FUNC或Action类做到这一点,但是这迫使我立刻声明整个函数签名。当我尝试使用代理,我得到一个编译错误说,它不能的方法组转换为代表。

我的工作轴向我试图让用户调用Web服务。什么我要的,是建立在Visual Studio代理类,然后通过在生成的功能的能力。函数签名并不重要,因为生成的code只使用函数名。不过,我想在函数的不是名称来传递的原因有两个:使用代理的Url属性的能力,如果网络服务不存在或Visual Studio更新一个编译器错误

 
公共无效AlertIt(对象o){
    Axial.DOM.Window.Alert(o.ToString());
}
公共无效CallAddService(){
    [对象]参数=新的对​​象[] {int.Parse(txtA.Text),int.Parse(txtB.Text)};
    Axial.ServerScript.CallWebService(新WSProxy.WS()添加,参数,AlertIt,AlertIt);
}类Axial.ServerScript {
    公共无效CallWebService(代表法,对象[]参数,动作<对象> successCallback,动作<对象> failureCallback){
        //翻译成JavaScript的(已经工作)
    }
}


解决方案

我想你想要的是:

 静态对象的InvokeMethod(委托方法,params对象[]参数){
    返回method.DynamicInvoke(参数);
}静态INT添加(INT A,INT B){
    返回A + B;
}静态无效测试(){
    Console.WriteLine(的InvokeMethod(新Func键< INT,INT,INT>(添加),5,4));
}

打印9。

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.

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)
    }
}

解决方案

I think what you want is:

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

Prints "9".

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

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