반응형
모르겠으니까 예제 외우자 낄낄낄~~~!!!
[8.Delegate와 Event예제 \ delegate.cs]
using System;
class MainApp
{
public delegate void Mix(string s); // 델리게이트 선언
public static void Coffee(string s)
{
Console.WriteLine("this Coffee is Mixed with {0} ", s);
}
public static void CoCoa(string s)
{
Console.WriteLine("this CoCoa is Mixed with {0} ", s);
}
public static void Main()
{
Mix Tea = new Mix(Coffee); //할당된 델리게이트는 Coffee 메서드를 참조
Tea("salt"); //Coffee 메서드를 참조하고 있으므로 Coffee("salt")를 실행
Tea = new Mix(CoCoa); //할당된 델리게이트는 CoCoa 메서드를 참조
Tea("milk"); //Coffee 메서드를 참조하고 있으므로 CoCoa("milk")를 실행
}
}
[8.Delegate와 Event예제 \ Coffee.cs]
using System;
class MainApp
{
public delegate void Stuff(); // 델리게이트 선언
public static void Sugar()
{
Console.WriteLine("Sugar");
}
public static void Cream()
{
Console.WriteLine("Cream");
}
public static void Milk()
{
Console.WriteLine("Milk");
}
public static void Coffee()
{
Console.WriteLine("Coffee");
}
public static void Main()
{
Stuff S = new Stuff(Sugar);
Stuff C = new Stuff(Cream);
Stuff M = new Stuff(Milk);
Stuff cafe = new Stuff(Coffee);
Console.WriteLine("비엔나 커피 만들기 : ");
Stuff Vienna = S + C + cafe; // 설탕 + 크림 + 커피 = 비엔나 커피 (Delegate의 합성)
Vienna();
Console.WriteLine();
Console.WriteLine("까페오레 만들기 : ");
Stuff CafeAuLait = S + M + cafe; // 설탕 + 우유 + 커피 = 까페오레
CafeAuLait();
Console.WriteLine();
Console.WriteLine("블랙커피 만들기 : ");
Stuff Black = CafeAuLait - M - S; // 커피 + 물 = 블랙커피
Black();
}
}
[8.Delegate와 Event예제 \ Event.cs]
using System;
class Client
{
private int ID;
public delegate void ClientService(object sender, EventArgs args);
public event ClientService Service;
public Client(int ID) // 생성자 : Client의 ID를 설정합니다.
{
this.ID = ID;
}
public int ClientID // ClientID 프로퍼티 : ID를 읽어옵니다.
{
get{ return this.ID; }
}
public void FireEvent() // 이벤트를 발생시킵니다.
{
if ( Service != null )
{
EventArgs args = new EventArgs();
Service(this, args);
}
}
}
class MainApp
{
public static void OnEvent(object sender, EventArgs args)
{
Client client = (Client)sender;
Console.WriteLine("고객번호 {0}, 경품 이벤트에 담청되셨습니다!.", client.ClientID);
}
public static void Main()
{
Client clentA = new Client(1);
clentA.Service += new Client.ClientService(OnEvent);
clentA.FireEvent();
Client clentB = new Client(2);
clentB.Service += new Client.ClientService(OnEvent);
clentB.FireEvent();
}
}
'.NET > C# Basic' 카테고리의 다른 글
프로퍼티 인덱서 (0) | 2008.10.15 |
---|---|
연산자 메서드 operator +(), operator-() , 연산자 오버로딩? (0) | 2008.10.15 |
static정적맴버 배열 연산자 is/as foreach 문 메서드 오버로딩 메서드 가변 인자 (0) | 2008.10.14 |
인터페이스(interface) 와 추상화클래스(abstract) 예제 (0) | 2008.10.14 |
Console.Read() 와 Console.ReadLine() 차이 (0) | 2008.10.10 |
흐름 제어 예제 기본문법 if for while swich foreach break continue (0) | 2008.10.10 |
C#을 시작하기위한 .... 오윤이의 그것 (0) | 2008.10.10 |
연산자 오버로딩 - 인덱스 (0) | 2008.10.10 |