using System;

namespace 무명메서드
{
    //[!] 대리자 선언
    public delegate void SayHandler(string msg);

    public class Button
    {
        public event SayHandler Click; //[1] 이벤트 생성

        public void OnClick(string msg) //[2] 이벤트 핸들러 생성
        {
            if (Click != null)
            {
                Click(msg);
            }
        }
    }

    public class Program
    {
        public static void Say(string msg)
        {
            Console.WriteLine(msg);
        }

        static void Main(string[] args)
        {
            //[1] 메서드 호출
            Program.Say("안녕"); Say("안녕");

            //[2] 대리자를 통해서 대신 호출
            SayHandler sh = new SayHandler(Program.Say);
            sh += new SayHandler(Program.Say);
            sh("방가"); // 실행

            //[3] 이벤트와 이벤트 처리기를 통해서 등록해서 호출
            Button btn = new Button();
            btn.Click += new SayHandler(Say); // 기본
            btn.Click += Say; // 축약형
            btn.OnClick("또봐");  // 실행

            //[4] 무명메서드 : 간단하게 메시지만 출력하는 기능이라면 함수사용하지 않고 그 자리에 delegate로 바꿔서 써준다.
            SayHandler hi = delegate(string msg) { Console.WriteLine(msg); };
            hi("언제"); hi("언제");
            Button button = new Button();
            button.Click += delegate(string msg) { Console.WriteLine(msg); };
            button.Click += delegate(string msg) { Console.WriteLine(msg); };
            button.OnClick("내일");

        }
    }
}

'.NET프로그래밍 > C# 3.5 SP1' 카테고리의 다른 글

57. 네임스페이스(Namespace)  (0) 2009.08.14
56. 클래스복습  (0) 2009.08.14
54. 이벤트(Event)  (0) 2009.08.13
53. 대리자(Delegate)  (0) 2009.08.13
알고리즘 - 11. 병합정렬(Merge)  (0) 2009.08.13
Posted by holland14
: