您的位置:首页 > 其它

Delegate 与 MulticastDelegate 委托的单波与多波模式

2009-03-04 00:01 351 查看
class TestDelegate
{
public delegate void EventHanding();
public event EventHanding OnFireEvnet;

protected void RegistEvent()
{
Delegate d1 = new EventHanding(test1);

Delegate d2 = new EventHanding(test2);

Delegate d3 = new EventHanding(test3);

Delegate d4 = new EventHanding(test4);

Delegate newEvent1 = Delegate.Combine(d1, d2);

Delegate newEvent2 = Delegate.Combine(d3, d4);

//新合并的委托是一个新的对象
if (Object.ReferenceEquals(d2, newEvent1))
{
string str = string.Empty;
}
if (d2.Method.ToString().CompareTo(newEvent1.Method.ToString())==0)
{
string str = string.Empty;
}

EventHanding newEvent = (EventHanding)Delegate.Combine(newEvent1, newEvent2);
OnFireEvnet += newEvent;
}

protected void FireEvent()
{
//单波
MulticastDelegate del = (MulticastDelegate)OnFireEvnet;
del.Method.Invoke(this, null);

//多波
OnFireEvnet();
}

int i = 0;
public void test1()
{
i++;

}
public void test2()
{
i++;
}
public void test3()
{
i++;

}
public void test4()
{
i++;
}

public static void Test()
{
TestDelegate test = new TestDelegate();
test.RegistEvent();
test.FireEvent();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: