【问题标题】:How to pass a function func as argument to another and then assignate this argument to a delegate variable? [duplicate]如何将函数 func 作为参数传递给另一个函数,然后将此参数分配给委托变量? [复制]
【发布时间】:2017-06-14 15:03:10
【问题描述】:

如何将函数用作另一个函数的参数并将其分配给委托

public class myClass
{
    public delegate void myDelegate(double x, string s);
    //declaration of   delegate
    public void func(double x, string s)
    {
      dosomethings...
    }
    // what is the declaration of the argument 'Function declaration'
    public void myFunction('Function declaration' function)
    { 
      myDelegate deFunc;
      deFunc = function;
    }
    }
    static void Main(string[] args)
    {
        myFunction(func);
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

Main 是静态的,所以在这种情况下,另一个方法也应该是静态的。例如:

    public delegate void myDelegate(double x, string s);
    //declaration of   delegate
    public static void func(double x, string s)
    {
        //dosomethings...
    }
    // what is the declaration of the argument 'Function declaration'
    public static void myFunction(myDelegate function)
    {
        myDelegate deFunc;
        deFunc = function;
    }

    static void Main(string[] args)
    {
        myFunction(func);
    }

【讨论】:

  • 好的。思考。
【解决方案2】:

您可以使用您在课堂上已经提供的定义:

public void myFunction(myDelegate del)
{ ... }

Action-delegate introduces in .NET 3.5,它是代表什么都不返回的快捷方式(void):

public void myFunction(Action<double, string> del)

在后一种情况下,您方法中的 deFunc 也应该是 Action&lt;double, string&gt; 类型,因为您不能将其转换为 myDelegate

请注意 delegate 是保留关键字,因此您应该在方法签名中将参数命名为不同的名称,例如del 或只是 func@delegate,前面逐字逐句 @

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-28
  • 2015-07-07
  • 2019-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-08-07
  • 2019-01-28
相关资源
最近更新 更多