1

我需要一些帮助来声明下面的 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
    }
}
4

2 回答 2

2

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

void Subscribe(OnCount callback)
于 2013-04-25T22:13:33.433 回答
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
    }
}
于 2013-04-26T12:47:00.040 回答