C#/복습

대리자, 익명 메서드

Game Client Lee Hwanguk 2023. 1. 23. 15:38

https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/delegates/

 

대리자 - C# 프로그래밍 가이드

C#의 대리자는 매개 변수 목록 및 반환 형식이 있는 메서드를 나타내는 형식입니다. 대리자는 메서드를 다른 메서드에 인수로 전달하는 데 사용됩니다.

learn.microsoft.com

https://learn.microsoft.com/ko-kr/dotnet/api/system.delegate?view=net-7.0 

 

Delegate 클래스 (System)

클래스 인스턴스와 해당 클래스의 인스턴스 메서드 또는 정적 메서드를 참조하는 데이터 구조체인 대리자를 나타냅니다.

learn.microsoft.com

#1. 대리자를 쓰지 않던 기존 방법(메서드에서 값을 return하고 다른 메서드의 매개변수로 이용)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class App
    {
        public App()
        {
            string contents = this.LoadFile(); //1.LoadFile에서 return받은 string을 contents에 할당 하고
            this.Print(contents); //2.cotents변수를 매개변수로 이용
        }

        private string LoadFile()
        {
            //파일 읽기 
            return "hello world!";
        }

        private void Print(string contents) //3.매개변수로 받은 contents를
        {
            //출력 
            Console.WriteLine(contents); //3.출력하는 매서드
        }
    }
}

#2.대리자를 이용하여 callback

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class App
    {
        //2.대리자 형식 정의
        delegate void MyDel(string contents);
        public App()
        {
            this.LoadFile();
        }

        private void LoadFile()
        {
            //파일 읽기
            Console.WriteLine("file loading....");
            //파일 다 읽음(이벤트 발생)
            //대리자 호출
            string contents = "hello";

            //3.대리자 변수 정의
            MyDel myDel;
            //4.대리자 인스턴스 생성(메서드 연결), 변수에 할당
            myDel = new MyDel(this.Print); //연결된 메서드 Print

            //callback 메서드 호출, 대리자 호출, 대리자 메서드 호출
            myDel(contents); //연결된 메서드에 contents를 매개변수로 할당
        }

        //1. 대리자에 연결할 메서드를 정의하자
        private void Print(string contents) //매개변수로 받은 contents값을
        {
            Console.WriteLine(contents); //출력하는 Print 메서드
        }
    }
}

#3. 메서드 매개변수로 대리자 넣기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class App
    {
        //2.대리자 형식 정의
        delegate void MyDel(string contents);
        public App()
        {
            //3. 대리자 변수 정의 
            MyDel myDel;

            //4. 대리자 인스턴스 생성 (메서드 연결), 변수에 할당 
            myDel = new MyDel(this.Print);

            this.LoadFile(myDel);
        }
        private void LoadFile(MyDel myDel)
        {
            //파일 읽기 
            Console.WriteLine("파일 읽는중...");
            //파일을 다 읽음 (이벤트) : LOAD_COMPLETE (상태)
            //대리자를 호출 

            string contents = "hello world!";   //<---- 파일에서 나온 문자열 

            //callback 메서드 호출, 대리자 호출, 대리자 메서드 호출                                     
            myDel(contents);

        }


        //1. 대리자에 연결할 메서드를 정의하자
        private void Print(string contents) //매개변수로 받은 contents값을
        {
            Console.WriteLine(contents); //출력하는 Print 메서드
        }
    }
}

#4. 익명메서드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class App
    {
       //2.대리자 형식 정의
       delegate int MyDel(int a, int b);
        public App()
        {
            //익명 메서드 연습

            //1.메서드를 구상한다, 두 수를 더해서 반환하는 메서드를 구상해보자
            //3.대리자 변수 정의
            //MyDel myDel;
            //4.대리자 인스턴스화 (메서드에 연결)
            MyDel mydel = delegate (int a, int b)
            {
                return a + b;
            };
            //5.대리자 호출, callback, 대리자 메서드 호출
            int result=mydel(2,3);
            Console.WriteLine(result);
        }
       
    }
}

#기존 대리자를 만드는 방법에서 더 간단해졌다, 머릿속으로 어떤 메서드를 호출할지 구상한다

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class App
    {
       //2.대리자 형식 정의
       delegate int MyDel(int a, int b);
       delegate void MyDel1(string name);
        public App()
        {
            //익명 메서드 연습

            //1.메서드를 구상한다, 두 수를 더해서 반환하는 메서드를 구상해보자
            //3.대리자 변수 정의
            //MyDel myDel;
            //4.대리자 인스턴스화 (메서드에 연결)
            MyDel mydel = delegate (int a, int b)
            {
                return a + b;
            };
            ////5.대리자 호출, callback, 대리자 메서드 호출
            int result = mydel(2, 3);
            Console.WriteLine(result);


            //MyDel1 mydel1;
            MyDel1 mydel1 = delegate (string name)
            {
                Console.WriteLine("{0}님",name);
            };
            mydel1("이환국");
        }
       
    }
}

#기존 방식보다 짧고 간결하다 머리속에서 꼬이지만 않는다면 정말 유용하다