C#/수업내용
[ C# 9일차 ] 대리자 delegate 연습2
왹져박사
2023. 1. 11. 14:36
대리자 사용 x
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study10
{
class App
{
//생성자
public App()
{
Console.WriteLine("App");
string contents = this.LoadFile();
this.Print(contents);
}
private string LoadFile()
{
//파일 읽기
return "hello world!";
}
private void Print(string contents)
{
//출력
Console.WriteLine(contents);
}
}
대리자 사용
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study10
{
class App
{
//2. 대리자 형식 정의
delegate void MyDel(string context);
//생성자
public App()
{
Console.WriteLine("App");
//3. 대리자 변수 정의
MyDel myDel;
//4. 대리자 인스턴스 생성(메서드 연결), 변수에 할당
//myDel = new MyDel(this.Print);
myDel = this.Print;
this.LoadFile(myDel);
}
private void LoadFile(MyDel myDel)
{
//파일 읽기
Console.WriteLine("파일 읽는중...");
//파일을 다 읽음 (이벤트) : LOAD_COMPLETE (상태)
//대리자를 호출
string contents = "hello world";
//myDel(contents); //callback 메서드 호출, 대리자 호출, 대리자 메서드 호출
//callback 메서드 호출, 대리자 호출, 대리자 메서드 호출
//null check 필요
if (myDel == null)
{
//출력x
}
else
{
myDel(contents); //출력, callback(Print)
}
}
//1. 대리자에 연결할 메서드 정의
private void Print(string contents)
{
//출력
Console.WriteLine(contents);
}
}
}