开发者

Having a function as an argument

开发者 https://www.devze.com 2023-04-02 18:16 出处:网络
I am trying to make a new Timers class to aid with my learning of c#. How would I let开发者_JAVA技巧 an argument for a function be a function?It\'s pretty simple. Just make the argument be some kind o

I am trying to make a new Timers class to aid with my learning of c#. How would I let开发者_JAVA技巧 an argument for a function be a function?


It's pretty simple. Just make the argument be some kind of delegate type, like Action or 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();
    }
    ...
}

You can call it like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消