본문 바로가기
C#/수업내용

[ C# 9일차 ] 대리자 delegate 연습2

by 왹져박사 2023. 1. 11.
728x90

대리자 사용 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);
        }
    }
}
728x90

'C# > 수업내용' 카테고리의 다른 글

[ C# 9일차 ] Func, Action 대리자  (0) 2023.01.11
[ C# 9일차 ] 익명메소드와 람다1  (0) 2023.01.11
[ C# 9일차 ] 대리자 delegate 연습1  (0) 2023.01.11
[ C# 9일차 ] char  (0) 2023.01.11
[ C# 8일차 ] 오버라이딩  (0) 2023.01.10