델리게이트와 이벤트를 활용한 콜벡메서드 예제
2022. 5. 24. 17:14ㆍSTUDY/C#
728x90
반응형
using System;
using System.Collections.Generic;
namespace Delegateex
{
class Program
{
static void Main(string[] args)
{
Teacher a = new Teacher();
a.Run();
}
}
}
namespace Delegateex
{
// 반환형이 없고 매개변수가 int형인 delegate를
// namespace단에 선언합니다.
public delegate void MyDel(int score);
class Teacher
{
public void Run()
{
// 학생 두명 생성
Student1 stu1 = new Student1();
Student2 stu2 = new Student2();
// 각각의 학생의 Event(Delegate)에 메서드를 구독시킨다.
stu1.Stu1Event += GetScore;
stu2.Stu1Event += GetScore;
stu1.Run();
stu2.Run();
}
private void GetScore(int score)
{
Console.WriteLine(string.Format("당신의 점수는 {0}점 입니다.", score));
}
}
}
namespace Delegateex
{
class Student1
{
// 네임스페이스 단에 선언된 Mydel을 이벤트형식으로 선언
public event MyDel Stu1Event;
public void Run()
{
int score = 80;
if (Stu1Event != null)
{
if (score > 70)
Stu1Event(score);
}
}
}
}
namespace Delegateex
{
class Student2
{
// 네임스페이스 단에 선언된 Mydel을 이벤트형식으로 선언
public event MyDel Stu2Event;
public void Run()
{
// 콜백메서드 호출
Stu2Event(100);
}
}
}
728x90
반응형
'STUDY > C#' 카테고리의 다른 글
델리게이트, 이벤트 (0) | 2022.06.01 |
---|---|
추상클래스, 인터페이스 연습용 (0) | 2022.05.24 |
11-15장 (0) | 2022.04.18 |
5-10장 (0) | 2022.04.18 |
1-4장 (0) | 2022.04.14 |