将方法作为参数传递

时间:2010-10-25 14:19:11

标签: c# .net-3.5

我希望能够将方法作为参数传递。

例如..

//really dodgy code
public void PassMeAMethod(string text, Method method)
{
  DoSomething(text);
  // call the method
  //method1();
  Foo();
}

public void methodA()
{
  //Do stuff
}


public void methodB()
{
  //Do stuff
}

public void Test()
{
  PassMeAMethod("calling methodA", methodA)
  PassMeAMethod("calling methodB", methodB)
}

我该怎么做?

6 个答案:

答案 0 :(得分:21)

您需要使用委托,这是一个表示方法的特殊类。您可以定义自己的委托或使用其中一个内置委托,但委托的签名必须与您想要传递的方法匹配。

定义自己的:

public delegate int MyDelegate(Object a);

此示例匹配一个返回整数并将对象引用作为参数的方法。

在你的例子中,methodA和methodB都没有参数返回void,所以我们可以使用内置的Action委托类。

以下是您修改的示例:

public void PassMeAMethod(string text, Action method)
{
  DoSomething(text);
  // call the method
  method();    
}

public void methodA()
{
//Do stuff
}


public void methodB()
{
//Do stuff
}

public void Test()
{
//Explicit
PassMeAMethod("calling methodA", new Action(methodA));
//Implicit
PassMeAMethod("calling methodB", methodB);

}

如您所见,您可以显式或隐式地使用委托类型,以适合您的方式。

答案 1 :(得分:7)

使用Action<T>

示例:

public void CallThis(Action x)
{
    x();
}

CallThis(() => { /* code */ });

答案 2 :(得分:5)

或Func&lt;&gt;

Func<int, string> func1 = (x) => string.Format("string = {0}", x);
PassMeAMethod("text", func1);

public void PassMeAMethod(string text, Func<int, string> func1)
{
  Console.WriteLine( func1.Invoke(5) );
}

答案 3 :(得分:2)

Delegates是您需要用来完成您要做的事情的语言功能。

以下是使用上面代码的示例(使用Action委托作为快捷方式):

//really dodgy code
public void PassMeAMethod(string text, Action method)
{
    DoSomething(text);
    method(); // call the method using the delegate
    Foo();
}

public void methodA()
{
    Console.WriteLine("Hello World!");
}    

public void methodB()
{
    Console.WriteLine("42!");
}

public void Test()
{
    PassMeAMethod("calling methodA", methodA)
    PassMeAMethod("calling methodB", methodB)
}

答案 4 :(得分:0)

以BrunoLM所做的为基础,因为这个例子很简短。

//really dodgy code
public void PassMeAMethod(string text, Action method)
{
  DoSomething(text);
  method();
  Foo();
}

// Elsewhere...

public static void Main(string[] args)
{
    PassMeAMethod("foo", () =>
        {
            // Method definition here.
        }
    );

    // Or, if you have an existing method in your class, I believe this will work
    PassMeAMethod("bar", this.SomeMethodWithNoParams);
}

答案 5 :(得分:0)

c#.net2.0 - 让我展示一下该主题的详细答案(pass-a-method-as-a-parameter)。 在我的场景中,我配置了一组 System.Timers.Timer -s,每个都使用不同的 _Tick 方法。

delegate void MyAction();

// members
Timer tmr1, tmr2, tmr3;
int tmr1_interval = 4.2, 
    tmr2_interval = 3.5;
    tmr3_interval = 1;


// ctor
public MyClass()
{
  ..
  ConfigTimer(tmr1, tmr1_interval, this.Tmr_Tick);
  ConfigTimer(tmr2, tmr2_interval, (sndr,ev) => { SecondTimer_Tick(sndr,ev); }); 
  ConfigTimer(tmr3, tmr3_interval, new MyAction((sndr,ev) => { Tmr_Tick((sndr,ev); }));
  ..
}

private void ConfigTimer(Timer _tmr, int _interval, MyAction mymethod)
{
  _tmr = new Timer() { Interval =  _interval * 1000 };
  // lambda to 'ElapsedEventHandler' Tick
  _tmr.Elpased += (sndr, ev) => { mymethod(sndr, ev); };
  _tmr.Start();
}

private void Tmr_Tick(object sender, ElapsedEventArgs e)
{
  // cast the sender timer
  ((Timer)sender).Stop();
  /* do your stuff here */
  ((Timer)sender).Start();
}

// Another tick method
private void SecondTimer_Tick(object sender, ElapsedEventArgs e) {..}