传递的方法作为参数 [英] Pass a method as an argument

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

问题描述

我如何通过一个方法作为参数?
我做这一切的时候在Javascript和需要使用匿名方法来传递PARAMS。我该怎么做它在C#?

 保护无效的MyMethod(){
    RunMethod(ParamMethod(世界));
}保护无效RunMethod(ArgMethod){
    MessageBox.Show(ArgMethod());
}保护字符串ParamMethod(字符串sWho){
    回归你好+ sWho;
}


解决方案

代表提供这种机制。一个快速的方法来做到这一点在C#3.0的例子是使用 Func键< TResult方式> 其中 TResult 字符串和lambda表达式

您code将随即成为:

 保护无效的MyMethod(){
    RunMethod(()=> ParamMethod(世界));
}保护无效RunMethod(Func键<串GT;的方法){
    MessageBox.Show(方法());
}保护字符串ParamMethod(字符串sWho){
    回归你好+ sWho;
}

不过,如果您使用的是C#2.0中,你可以使用匿名委托来代替:

  //声明为我们传递方法的委托。
委托串MyDelegateType();保护无效的MyMethod(){
    RunMethod(代表
    {
        返回ParamMethod(世界);
    });
}保护无效RunMethod(MyDelegateType法){
    MessageBox.Show(方法());
}保护字符串ParamMethod(字符串sWho){
    回归你好+ sWho;
}

How do I pass a method as an argument? I do this all the time in Javascript and need to use anonymous methods to pass params. How do I do it in c#?

protected void MyMethod(){
    RunMethod(ParamMethod("World"));
}

protected void RunMethod(ArgMethod){
    MessageBox.Show(ArgMethod());
}

protected String ParamMethod(String sWho){
    return "Hello " + sWho;
}

解决方案

Delegates provide this mechanism. A quick way to do this in C# 3.0 for your example would be to use Func<TResult> where TResult is string and lambdas.

Your code would then become:

protected void MyMethod(){
    RunMethod(() => ParamMethod("World"));
}

protected void RunMethod(Func<string> method){
    MessageBox.Show(method());
}

protected String ParamMethod(String sWho){
    return "Hello " + sWho;
}

However, if you are using C#2.0, you could use an anonymous delegate instead:

// Declare a delegate for the method we're passing.
delegate string MyDelegateType();

protected void MyMethod(){
    RunMethod(delegate
    {
        return ParamMethod("World");
    });
}

protected void RunMethod(MyDelegateType method){
    MessageBox.Show(method());
}

protected String ParamMethod(String sWho){
    return "Hello " + sWho;
}

这篇关于传递的方法作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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