将委托订阅事件分配给List

时间:2017-01-31 13:33:42

标签: c# events delegates onchange

这是我的问题:我有一个我从另一个班级订阅的代表,这没关系。我喜欢的是,每次订阅此委托时,它都会引发一个事件,告诉我调用列表已更改,以及+1或-1 ... 我在调用列表中搜索了一个Onchange事件,但没有找到任何东西..

Form1中:

namespace EventsOnDelegates
{
public delegate void DEL_delegate1(Double AValue);
public delegate void DEL_delegate2(Boolean AsecondValue);

public partial class Form1 : Form
{
    public DEL_delegate1 SetValueCbk;
    public EventHandler InvocationListChange;
    private Form2 FormwithLabel;
    int invoclength;
    public Form1()
    {
        InitializeComponent();
        FormwithLabel = new Form2(this);
        FormwithLabel.Show();  
        /*the question part*/
        /*I'd like to add an onchange event that tells me if the invocation list has changed and how + or -*/
        InvocationListChange += new EventHandler(SetValueCbk.GetInvocationList(),InvocationListHaschanged);          
    }
    protected virtual void InvocationListHaschanged(object sender, EventArgs e)
    {
    invoclength = SetValueCbk.GetInvocationList().Length;
    label1.Text = Convert.ToString(invoclength);
    }
    private void button1_Click(object sender, EventArgs e)
    {
        Random newRandNum = new Random();
        Double newNumber = newRandNum.NextDouble();
        SetValueCbk(newNumber);
    }
}
}

窗体2:

public partial class Form2 : Form
{
    public Form2(){}
    public Form2(Form1 Form1link)
        :this()
    {
        InitializeComponent();
        Form1link.SetValueCbk  += new DEL_delegate1(this.SetValueCbkFN);
    }
    protected void SetValueCbkFN(Double value)
    {
        label1.Text = Convert.ToString(value);
    }
}

感谢您的帮助!!

1 个答案:

答案 0 :(得分:1)

您可以将explicit event declaration用于event字段:

private EventHandler meEvent;

public event EventHandler MeEvent
{
    add { meEvent += value; MeEventInvocationListChanged(); }
    remove { meEvent -= value; MeEventInvocationListChanged(); }
}

编辑: (将此问题纳入您的问题)

而不是您可以创建的InvocationListHasChanged方法:

void InvokationListChanged(int dir)
{
    string msg = dir < 0 ? "Someone unsubscribed from the event" : "Someone subscribed to the event";
    if(InvokeRequired)
    {
        Invoke( new MethodInvoker( () => { label1.Text = msg; });
    }
    else
    {
        label1.Text = msg;
    }
}

然后将public DEL_delegate1 SetValueCbk;更改为:

private DEL_delegate1 m_SetValueCbk;

public event Del_delegate1 SetValueCbk
{
    add { m_SetValueCbk+= value; InvokationListChanged(1); }
    remove { m_SetValueCbk-= value; InvokationListChanged(-1); }
}

现在,只要其他对象订阅SetValueCbk,您的label1.Text就会更改为"Someone subscribed to the event",只要某个对象取消订阅SetValueCbk,您的label1.Text就会更改为{ {1}}