델리게이터를 응용하여 사용하는 몇 가지 방법을 알아보겠습니다.
[콜백 메서드]
델리게이터는 콜백 메서드를 구현할 때 유용합니다. 콜백 메서드를 간단하게 정의하면 매개변수로 전달하는 메서드입니다.
예를 들어, 비동기 작업이 완료된 후 특정 메서드를 호출할 수 있습니다.
기본적으로 다음 형태를 따릅니다.
public delegate void CustomDelegate(); // 델리게이터 선언
public void Method(CustomDelegate customDelegate)
{
// 매개변수로 전달된 델리게이터(메서드)를 호출합니다.
CustomDelegate();
}
두 가지 예제를 살펴보겠습니다.
// 콜백 메서드 예제 1
using System;
using System.Threading;
public delegate void Callback(string result);
class Program
{
static void Main()
{
// StartAsyncTask 메서드는 비동기 작업을 시작하고, 작업이 완료되면 callback 델리게이터를 호출합니다
StartAsyncTask("Test Task", TaskCompleted);
}
static void StartAsyncTask(string taskName, Callback callback)
{
Console.WriteLine("Starting task: " + taskName);
Thread.Sleep(2000); // Simulate a time-consuming task
callback("Task completed");
}
static void TaskCompleted(string result)
{
Console.WriteLine(result);
}
}
// 콜백 메서드 예제 2
using System;
using System.Collections.Generic;
class Student
{
// 학생의 이름과 점수를 저장하는 속성
public string Name { get; set; }
public double Score { get; set; }
// 생성자를 통해 이름과 점수를 초기화
public Student(string name, double score)
{
this.Name = name;
this.Score = score;
}
// ToString() 메서드 오버라이딩
public override string ToString()
{
return this.Name + " : " + this.Score;
}
}
class Students
{
// 학생 목록을 저장하는 리스트
private List<Student> listOfStudent = new List<Student>();
// 학생 정보를 출력하는 델리게이터 선언
public delegate void PrintProcess(Student student);
// 학생 목록에 학생 추가
public void Add(Student student)
{
listOfStudent.Add(student);
}
// 기본 출력 메서드: 람다 식을 사용해 간단히 학생 정보 출력
public void Print()
{
Print((student) =>
{
Console.WriteLine(student);
});
}
// 콜백 메서드: 외부에서 정의한 출력 프로세스를 사용해 학생 정보 출력
public void Print(PrintProcess process)
{
foreach (var item in listOfStudent)
{
// 콜백 메서드에 매개변수를 전달해 호출
process(item);
}
}
}
class Program
{
static void Main(string[] args)
{
// Students 클래스의 인스턴스를 생성
Students students = new Students();
// 학생 목록에 두 명의 학생 추가
students.Add(new Student("윤인성", 4.2));
students.Add(new Student("연하진", 4.4));
// 기본 출력 메서드 호출
students.Print();
// 커스텀 출력 메서드 호출: 이름과 학점을 각각 출력
students.Print((student) =>
{
Console.WriteLine(); // 줄바꿈
Console.WriteLine("이름 : " + student.Name);
Console.WriteLine("학점 : " + student.Score);
});
}
}
'C# > 프로그래밍 고급' 카테고리의 다른 글
C# 프로그래밍 고급 - 11. Linq (0) | 2024.05.30 |
---|---|
C# 프로그래밍 고급 - 10. 델리게이터와 이벤트 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 08. 델리게이터 종류 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 07. 람다식 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 06. 델리게이터 (0) | 2024.05.30 |