Code/C#
[C#] Delegate & Event 예제 코드
Hide Code
2007. 11. 23. 20:37
Delegate & Event 예제
간단한 Delegate & Event 예제 입니다.
아래에서 주의 할 점은 public event 를 부를 수 있는 것은 그 event 가 속해있는 class의 method 뿐이라는 것입니다.
Anonymous Method 의 사용법도 눈여겨보시기 바랍니다.
Anonymous Method 를 사용할 때, close brace " } " 다음에 세미콜론 " ; " 을 붙여야합니다.
간단한 Delegate & Event 예제 입니다.
아래에서 주의 할 점은 public event 를 부를 수 있는 것은 그 event 가 속해있는 class의 method 뿐이라는 것입니다.
Anonymous Method 의 사용법도 눈여겨보시기 바랍니다.
Anonymous Method 를 사용할 때, close brace " } " 다음에 세미콜론 " ; " 을 붙여야합니다.
using System;
namespace DelegateSample
{
class Program
{
static void Main(string[] args)
{
Human Tom = new Human();
Tom.ActionDelegate += new Action(Tom.Speak);
Tom.ActionDelegate += Tom.Shout;
// Anonymous Method
Tom.ActionDelegate += delegate(string words)
{
Console.WriteLine("Anonymous:" + words);
};
Tom.ActionDelegate("Direct Called Delegate");
Tom.RaiseActionDelegate("Delegate Raised by Method");
Tom.ActionEvent += new Action(Tom.Speak);
Tom.ActionEvent += Tom.Shout;
// Anonymous Method
Tom.ActionEvent += delegate(string words)
{
Console.WriteLine("Anonymous:" + words);
};
// A public event can only be raised
// by methods within the class that defines it.
// Tom.ActionEvent("Direct Called Event"); // Compile Error.
Tom.RaiseActionEvent("Event Raised by Method");
}
delegate void Action(string words);
class Human
{
public void Speak(string words)
{
Console.WriteLine("Speak:" + words);
}
public void Shout(string words)
{
Console.WriteLine("Shout:" + words);
}
public void RaiseActionDelegate(string words)
{
if (this.ActionDelegate != null)
{
this.ActionDelegate(words);
}
}
public void RaiseActionEvent(string words)
{
if (this.ActionEvent != null)
{
this.ActionEvent(words);
}
}
public Action ActionDelegate;
public event Action ActionEvent;
}
}
}