【问题标题】:Pass a method as an argument将方法作为参数传递
【发布时间】:2010-11-16 18:02:18
【问题描述】:

如何将方法作为参数传递? 我一直在 Javascript 中这样做,并且需要使用匿名方法来传递参数。如何在 C# 中做到这一点?

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

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

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

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    Delegates 提供这种机制。对于您的示例,在 C# 3.0 中执行此操作的一种快速方法是使用 Func<TResult> 其中 TResultstring 和 lambdas。

    您的代码将变为:

    protected void MyMethod(){
        RunMethod(() => ParamMethod("World"));
    }
    
    protected void RunMethod(Func<string> method){
        MessageBox.Show(method());
    }
    
    protected String ParamMethod(String sWho){
        return "Hello " + sWho;
    }
    

    但是,如果您使用的是 C#2.0,则可以改用匿名委托:

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

    【讨论】:

    • 这不会编译。 RunMethod 需要一个 Func 你传递给它 Func
    【解决方案2】:

    您的 ParamMethod 是 Func 类型,因为它接受一个字符串参数并返回一个字符串(请注意,尖括号中的最后一项是返回类型)。

    所以在这种情况下,你的代码会变成这样:

    protected void MyMethod(){
        RunMethod(ParamMethod, "World");
    }
    
    protected void RunMethod(Func<String,String> ArgMethod, String s){
        MessageBox.Show(ArgMethod(s));
    }
    
    protected String ParamMethod(String sWho){
        return "Hello " + sWho;
    }
    

    【讨论】:

    • 感谢您的回答。我得到一个编译错误'...RunMethod(Func,String) 有一些无效的参数。
    • 您使用的是哪个版本的 C#?
    【解决方案3】:
    【解决方案4】:
    protected String ParamMethod(String sWho)
    {
        return "Hello " + sWho;
    }
    
    protected void RunMethod(Func<string> ArgMethod)
    {
        MessageBox.Show(ArgMethod());
    }
    
    protected void MyMethod()
    {
        RunMethod( () => ParamMethod("World"));
    }
    

    () =&gt; 很重要。它从Func&lt;string, string&gt; 创建匿名Func&lt;string&gt;,即ParamMethod。

    【讨论】:

      【解决方案5】:
      protected delegate String MyDelegate(String str);
      
      protected void MyMethod()
      {
          MyDelegate del1 = new MyDelegate(ParamMethod);
          RunMethod(del1, "World");
      }
      
      protected void RunMethod(MyDelegate mydelegate, String s)
      {
          MessageBox.Show(mydelegate(s) );
      }
      
      protected String ParamMethod(String sWho)
      {
          return "Hello " + sWho;
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-09
        • 2019-02-22
        • 2012-06-08
        • 2018-11-10
        • 1970-01-01
        • 2013-09-11
        • 2011-04-30
        • 2021-04-30
        相关资源
        最近更新 更多