2011-09-06 95 views

回答

6

这很简单。只需使参数为某种delegate类型,如ActionFunc

void PassAnAction(Action action) 
{ 
    action(); // call the action 
} 

T PassAFunction<T>(Func<T> function) 
{ 
    return function(); 
} 
+0

我将如何使用通过一个动作?假设我想显示一个Hello World消息框。 – Michael

+0

@Michael:类似这样的:'PassAnAction((()=> ShowMessageBox(“Hello world”))'。 (我不知道你用什么来显示消息框,但希望能给你一个想法。) – StriplingWarrior

1
public class MyTimer { 
    private readonly Action _fireOnInterval; 

    public MyTimer(Action fireOnInterval, TimeSpan interval, ...) { 
     if (fireOnInterval == null) { 
      throw new ArgumentNullException("fireOnInterval"); 
     } 
     _fireOnInterval = fireOnInterval; 
    } 

    private void Fire() { 
     _fireOnInterval(); 
    } 
    ... 
} 

你可以这样调用:

new MyTimer(() => MessageBox.Show("Elapsed"), TimeSpan.FromMinutes(5), ...)