티스토리 뷰

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 " } " 다음에 세미콜론 " ; " 을 붙여야합니다.

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;
}
}
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함