.NET프로그래밍/C# 3.5 SP1

54. 이벤트(Event)

holland14 2009. 8. 13. 17:31


==> 이벤트.cs


using System;

public class 이벤트
{
    public static void Main()
    {
        //[1] 다중메서드 호출
        Hello.Hi1(); Hello.Hi2();

        //[2] 대리자 호출
        Say say;
        say = new Say(Hello.Hi1);
        say += new Say(Hello.Hi2);
        say();

        //[3] 이벤트와 핸들러로 호출
        Button btn = new Button();
        btn.Click += new Say(Hello.Hi1);
        btn.Click += new Say(Hello.Hi2);
        btn.OnClick(); // 실행

    }
}



==============================================================================================


==> Button.cs



using System;
//[!] 대리자
public delegate void Say();

public class Button
{
    //[!] 이벤트 : Click
    public event Say Click; // 형식 : 지정자 + event + 대리자이름 + 이벤트이름;
    
    //[!] 이벤트 처리기(핸들러)
    public void OnClick()
    {
        if (Click != null)
        {
            Click();
        }
    }
}

public class Hello
{
    public static void Hi1()
    {
        Console.WriteLine("안녕");
    }

    public static void Hi2()
    {
        Console.WriteLine("반가워");
    }

}