c#传递需要订阅事件的方法

时间:2013-04-25 22:12:30

标签: c# events delegates arguments action

我需要一些帮助来声明下面的Subscribe()方法。我想要拦截任何想要注册未来更新并告诉他们之前事件的人。

class Test
{
    public delegate void OnCount(int nCount);
    protected event OnCount _event;

    Test()
    {
        _event += countHandler; // This subscribes ok
        _event(6);

        Subscribe(countHandler); // I would like to pass this
    }

    void countHandler(int n) { int m = n; }

    void Subscribe(**Action<int>** callback) // Not sure how to declare argument (doesn't compile)
    {
        _event += callback;      // Subscribe to future values (doesn't compile)
        callback(5);             // Pass current/previous values
    }
}

2 个答案:

答案 0 :(得分:2)

您通常使用与事件相同的委托类型:

void Subscribe(OnCount callback)

答案 1 :(得分:0)

我刚想通了:

public class Test
{
    public delegate void OnCount(int nCount);
    protected event OnCount _event;

    public Test()
    {
        Subscribe(countHandler); // Pass method to callback
    }

    void countHandler(int n) { System.Diagnostics.Debug.WriteLine("n:" + n.ToString()); }

    void Subscribe(Action<int> callback)
    {
        _event -= new OnCount(callback); // Avoid re-subscriptions
        _event += new OnCount(callback); // Subscribe to future values 
        callback(5);                     // Pass current values
    }
}