委托使用(2)
class ClassWithDelegate
{
public delegate int DelegateThatReturnsInt();
public DelegateThatReturnsInt theDelegate;
public void Run()
{
for (; ; )
{
Thread.Sleep(500);
if (theDelegate != null)
{//第一个方法DisplayCounter()(由FirstSubscriber调用),返回1,2,3,4,5.但是这些值都将被第二个方法返回的值所覆盖
//我的目的是依次显示每个方法调用的结果。为此,必须接管多重委托所封装方法调用的职责。
foreach (DelegateThatReturnsInt del in theDelegate.GetInvocationList())
{
int result = del();
Console.WriteLine("Delegate fired! Returned result:{0}", result.ToString());
}
Console.WriteLine();
}
}
}
}
class FirstSubscriber
{
private int myCounter = 0;
public void Subscribe(ClassWithDelegate theClassWithDelegate)
{
theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturnsInt(DisplayCounter);//委托实例化 //theClassWithDelegate.theDelegate +=DisplayCounter可以写成这样
//也可以之间用匿名过程,可以把DisplayCounter()函数去掉
// theClassWithDelegate.theDelegate +=delegate()
//{
// return ++myCounter;
// };
}
public int DisplayCounter()
{
return ++myCounter;
}
}
class SecondSubscriber
{
private int myCounter = 0;
public void Subscriber1(ClassWithDelegate theClassWithDelegate)
{
theClassWithDelegate.theDelegate += new ClassWithDelegate.DelegateThatReturnsInt(DisplayCounter1);//委托实例化
}
public int DisplayCounter1()
{
return myCounter += 2;
}
}
ClassWithDelegate classWithDelegate = new ClassWithDelegate();
FirstSubscriber firstSubscriber = new FirstSubscriber();
firstSubscriber.Subscribe(classWithDelegate);
SecondSubscriber secondSubscriber = new SecondSubscriber();
secondSubscriber.Subscriber1(classWithDelegate);
classWithDelegate.Run();