0
我正在尝试制作一个新的Timers类来帮助我学习c#。我如何让一个函数的参数成为一个函数?具有作为参数的函数
我正在尝试制作一个新的Timers类来帮助我学习c#。我如何让一个函数的参数成为一个函数?具有作为参数的函数
这很简单。只需使参数为某种delegate
类型,如Action
或Func
。
void PassAnAction(Action action)
{
action(); // call the action
}
T PassAFunction<T>(Func<T> function)
{
return function();
}
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), ...)
我将如何使用通过一个动作?假设我想显示一个Hello World消息框。 – Michael
@Michael:类似这样的:'PassAnAction((()=> ShowMessageBox(“Hello world”))'。 (我不知道你用什么来显示消息框,但希望能给你一个想法。) – StriplingWarrior