C# 具有作为参数的函数

C# 具有作为参数的函数,c#,function,C#,Function,我正在尝试建立一个新的计时器类来帮助我学习c。如何让函数的参数成为函数?这很简单。只需将参数设置为某种委托类型,如Action或Func 你可以这样称呼它: new MyTimer(() => MessageBox.Show("Elapsed"), TimeSpan.FromMinutes(5), ...) 我将如何使用传递操作?假设我想显示一个Hello World消息框。@Michael:类似这样的内容:PassAnAction=>ShowMessageBoxHello World。

我正在尝试建立一个新的计时器类来帮助我学习c。如何让函数的参数成为函数?

这很简单。只需将参数设置为某种委托类型,如Action或Func

你可以这样称呼它:

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

我将如何使用传递操作?假设我想显示一个Hello World消息框。@Michael:类似这样的内容:PassAnAction=>ShowMessageBoxHello World。我不知道你用什么来显示消息框,但希望这能给你一个想法。
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), ...)