如何在C#中将函数作为参数传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/380198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 01:17:21  来源:igfitidea点击:

How to pass a function as a parameter in C#?

c#reflection

提问by Dan Goldstein

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.

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

I'm working on Axialand 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.

我在Axial 上工作,我正在尝试允许用户调用 Web 服务。我想要的是能够创建 Visual Studio 代理类,然后传入生成的函数。函数签名无关紧要,因为生成的代码仅使用函数名称。但是,出于两个原因,我想传入函数而不是名称:能够使用代理的 Url 属性,如果 Web 服务不存在或在 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)
    }
}

采纳答案by P Daddy

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".

打印“9”。

回答by dbones

please have a look at using delegates here is a great example

请看看这里使用委托是一个很好的例子

Delegate Example

委托示例

why are you using reflection? will there ever be a different number of params? or do you know the method signture will remain constant (also remember C# supports the params[] keyword)

你为什么使用反射?会有不同数量的参数吗?或者你知道方法签名将保持不变(还记得 C# 支持 params[] 关键字)

params c#

参数 c#

HTH

HTH

Bones

骨头

回答by Jon Limjap

You should have a delegate first

你应该先有一个代表

delegate int Operation(int a, int b)

then it becomes:

然后它变成:

public void InvokeMethod(Operation method, object target, object param)
{
    method((int) target, (int) param);
}

No need for any call to Invoke.

不需要对 Invoke 进行任何调用。

As with dbone I'm unsure why you would need a params[] array. Would you clarify the expanded usage for the params?

与 dbone 一样,我不确定为什么需要 params[] 数组。你会澄清参数的扩展用法吗?

Also, I'll have to correct something in your question though, because it will cause a compilation error :p

另外,我必须纠正您的问题中的某些内容,因为它会导致编译错误:p

回答by Mark Carpenter

Something like this ought to work for you:

像这样的事情应该适合你:

delegate int MyDelegate(int a, int b);
public int Add(int a, int b) {
    return a + b;
}
public void InvokeMethod(Delegate method, object[] param) {
    Console.WriteLine(method.DynamicInvoke(param));
}
public Form1() {       
    InitializeComponent();
    InvokeMethod(new MyDelegate(Add), new object[] { 1, 2 });
}

Good luck!

祝你好运!

回答by Jon Skeet

Converting a method group, anonymous method or lambda expression to a delegate requires the compiler to know the exact delegate type. However, you could potentially use lambda expressions and captured variables to make this simpler:

将方法组、匿名方法或 lambda 表达式转换为委托需要编译器知道确切的委托类型。但是,您可以潜在地使用 lambda 表达式和捕获的变量来简化此操作:

public void InvokeMethod(Action action)
{
    action();
}

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

public void Test()
{    
    InvokeMethod(() => Add(2, 3));
}

That basically delays invocation in the normal way, but by wrapping the actual call to Addin a plain Actiondelegate.

这基本上以正常方式延迟调用,但通过将实际调用包装Add在普通Action委托中。

If that doesn't fulfil your requirements, perhaps you can tell us a bit more about what you're really trying to achieve.

如果这不能满足您的要求,也许您可​​以告诉我们更多有关您真正想要实现的目标的信息。

EDIT: If this is generated code, you can cast to a Func<...>with the right type arguments - assuming there aren't too many. Other than that, there's no real way of just passing in a method group. There's been occasional calls for an "infoof(...)" operator (like typeof but for members) which would give you a MemberInfo, but that doesn't actually exist.

编辑:如果这是生成的代码,您可以Func<...>使用正确的类型参数强制转换为 a - 假设没有太多。除此之外,没有真正的方法可以只传递一个方法组。偶尔会调用“infoof(...)”操作符(类似于 typeof 但对于成员),它会给你一个 MemberInfo,但实际上并不存在。

回答by Jarek

Look at Functional Programming Seriesby Justin Etheredge. You should find solution to your problem there.

查看Justin Etheredge 的函数式编程系列。您应该在那里找到解决问题的方法。

回答by Arup C

Say If you need to pass the method as parameter as well as you need to catch the return value for further processing . Then the above examples will work fine . But say if you need to pass a method with void return type then you need to create one more version of the InvokeMethod function. Check the example below.

说如果您需要将方法作为参数传递以及您需要捕获返回值以进行进一步处理。那么上面的例子就可以正常工作了。但是如果你需要传递一个返回类型为 void 的方法,那么你需要创建一个 InvokeMethod 函数的另一个版本。检查下面的示例。

private static T retry<T>(Delegate method, params object[] args)
{
    for (int i = 0; i <= 3; i++)
    {
        try
        {
            return (T)method.DynamicInvoke(args);
        }
        catch (Exception ex)
        {
            if (i == 3)
            {
                logMessage(ex.Message);
            }
            Console.WriteLine("Retry count " + i);
            Thread.Sleep(10);
        }
    }
    return default(T);
}

private static void retry2(Delegate method, params object[] args)
{
    for (int i = 0; i <= 3; i++)
    {
        try
        {
            method.DynamicInvoke(args);
            break;
        }
        catch (Exception ex)
        {
            if (i == 3)
            {
                logMessage(ex.Message);
                //return default(T);
            }
            Console.WriteLine("Retry count " + i);
            Thread.Sleep(10);
        }
    }
}
static bool isSuccess = true;
static void logMessage(string msg)
{
    isSuccess = false;
    Console.WriteLine(msg);
}

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

static void Add2(int a, int b)
{
    int c = a + b;
    Console.WriteLine(c);
}

static void Main(string[] args)
{
    int d = retry<int>(new Func<int, int, int>(Add), 6, 7.7);
    Console.Write("  " + d + "\n"+isSuccess);

    retry2(new Action<int, int>(Add2), 45, 60);

    Console.ReadKey();
}

回答by dns

This is much simple example, to programmer who already familiar with (C/C++/VB.NET/Python)-style pass function by pointer/ref(with C# delegate):

这是一个非常简单的例子,对于已经熟悉 ( C/C++/VB.NET/Python)-stylepass function by pointer/ref(with C# delegate) 的程序员:

        delegate void CALLBACK(String s);
        static void Main(string[] args)
        {

            Get("some string", testfunc);

            Util.pause();
        }

        static void Get(String s, CALLBACK x)
        {
            x(s);
        }


        static void testfunc(String s)
        {
            Console.WriteLine(s);
        }