C#/연습장

대리자 (익명메서드 + 람다식)

Game Client Lee Hwanguk 2023. 1. 11. 16:29

 

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

namespace Study12
{
    class App
    {
        //생성자
        public App()
        {
            this.LoadFile((str) =>
            {
                Console.WriteLine(str); //hello world!
            }); //람다문 (익명메서드) 매개변수가 1개 있는 익명 메서드
                //반환값이 없음으로 Action 대리자를 사용하자
                //Action 대리자는 매개변수를 0~17개 지원
                //Action<T>
                //일반화를 먼저 다시 복습해야겠다

        }

        private void LoadFile(Action<string>callback)
        {
            //파일을 로드한다(읽는다)
            //파일에 있는 문자열 값을 읽어온다
            string str = "hello world!";
            callback(str);
        }






    }
}

#제너릭을 다시 봐야할 필요가 있다

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

namespace Study12
{
    class App
    {
        //생성자
        public App()
        {
            this.LoadScene(() =>
            {
                Console.WriteLine("씬 로드 완료");
            }); //익명메서드 , 매개변수 x, 반환타입 x

        }

        private void LoadScene(Action callback)
        {
            callback();
        }

        






    }
}

#class를 추가한 연습

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

namespace Study12
{
    internal class Hero
    {
        public Hero() {
        }
        public void Move(Action callback )
        {
            Console.WriteLine("이동중...");
            callback();
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study12
{
    class App
    {
        //생성자
        public App()
        {
            Hero hero = new Hero();
            hero.Move(() =>
            {
                Console.WriteLine("이동 완료");
            });

        }

       

        






    }
}

#

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

namespace Study12
{
    class App
    {
        //생성자
        public App()
        {
            Hero hero = new Hero();
            hero.onMoveComplete = () =>
            {
                Console.WriteLine("이동완료");
            };
            hero.Move(); //이동이 완료되면 대리자를 호출
            //이동중...
            //이동완료
        }

       

        






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

namespace Study12
{
    internal class Hero
    {
        public Action onMoveComplete; //해당 값을 알아야한다. 반환값이 없음으로 Action 타입
        public Hero() 
        {

        }
        public void Move()
        {
            Console.WriteLine("이동중...");
            this.onMoveComplete();
        }
    }
}