我已经创建了一个非常简单的虚拟程序来理解代表和事件。在我的下面的程序中,我简单地调用一个方法。当我调用一个方法时,有五种方法在委托和事件的帮助下自动调用。代表和事件
请看看我的程序,并让我知道我错了或正确的地方,因为这是我第一次使用代表和事件。
using System;
namespace ConsoleApplication1
{
public delegate void MyFirstDelegate();
class Test
{
public event MyFirstDelegate myFirstDelegate;
public void Call()
{
Console.WriteLine("Welcome in Delegate world..");
if (myFirstDelegate != null)
{
myFirstDelegate();
}
}
}
class AttachedFunction
{
public void firstAttachMethod()
{
Console.WriteLine("ONE...");
}
public void SecondAttachMethod()
{
Console.WriteLine("TWO...");
}
public void thirdAttachMethod()
{
Console.WriteLine("THREE...");
}
public void fourthAttachMethod()
{
Console.WriteLine("FOUR...");
}
public void fifthAttachMethod()
{
Console.WriteLine("FIVE...");
}
}
class MyMain
{
public static void Main()
{
Test test = new Test();
AttachedFunction attachedFunction = new AttachedFunction();
test.myFirstDelegate += new MyFirstDelegate(attachedFunction.firstAttachMethod);
test.myFirstDelegate += new MyFirstDelegate(attachedFunction.SecondAttachMethod);
test.myFirstDelegate += new MyFirstDelegate(attachedFunction.thirdAttachMethod);
test.myFirstDelegate += new MyFirstDelegate(attachedFunction.fourthAttachMethod);
test.myFirstDelegate += new MyFirstDelegate(attachedFunction.fifthAttachMethod);
test.Call();
Console.ReadLine();
}
}
}
它有什么问题吗?你没有提出问题 – Andrey 2010-10-21 16:04:45
看起来像一个很好的实现如何使用代表给我。如果你愿意,你可以使用C#2.0和更高级的语法糖代替'+ = new MyFirstDelete(methodName);',只需要'+ = methodName;'。此外,匿名代表也可以随时处理。 – 2010-10-21 16:09:41
@Jesse ...谢谢..我将使用+ = methodName :) – 2010-10-21 17:28:10