C#/복습

람다식(문),Action, Func

Game Client Lee Hwanguk 2023. 1. 23. 21:57

https://learn.microsoft.com/ko-kr/dotnet/csharp/language-reference/operators/lambda-expressions

 

람다 식 - 람다 식 및 익명 함수

익명 함수 및 식 본문 멤버를 만드는 데 사용되는 C# 람다 식입니다.

learn.microsoft.com

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();
        public App()
        {
            //람다식 연습

            //1. 메서드 생각  (두수의 합을 반환하는 메서드)

            //3. 대리자 변수 정의 
            MyDel del;

            //4. 대리자 인스턴스화 (메서드) , 익명메서드 (람다)
            //익명 메서드 
            del = delegate (int a, int b) {
                return a + b;
            };
            Console.WriteLine(del(1,3));

            //람다 썼을 경우 (=>연산자를 통해 사용)
            del = (int a, int b) => {
                return a + b;
            };
            Console.WriteLine(del(2,4));

            //람다문 + 형식유추 (int 형식까지 유추할수있다)
            del = (a, b) => {
                return a + b;
            };
            Console.WriteLine(del(3,5));

            //람다식+형식유추(람다문과 다르게 {}블록도 생략할수있다
            del=(a,b)=>a+ b;
            Console.WriteLine(del(4,6));

            //매개변수가 없을경우
            MyDel1 mydel1 = () => { Console.WriteLine("hello world"); };
            mydel1();

            //Func<T,T>,Action<T,T> -class에서 형식 정의도 필요가 없다
            //Func -> 반환값이 있을경우 , Action ->반환값이 없는경우

            Func<int> func0 = () => { return 0; }; //return 값 0을 반환하는 Func , <반환타입의형식>
            Func<int, int, int> func2 = (c, d) => { return c + d; }; //문람다, <type, c의 type, d의 type>
            Console.WriteLine(func2(4,2)); //6

            Func<int, int, int> func1 = (a, b) => a - b; //식람다, <type, a의 type, b의 type> 
            Console.WriteLine(func1(3,2)); //1

            Action<int> action0 = (a) => { Console.WriteLine(a); }; //반환값이 없는 Action 문 람다
            Action<string> action1=(name)=>Console.WriteLine(name); //Action 식 람다

            //int b=action0(2); //Action은 void, 반환없음
            //string name0=action1("이환국");//Action은 void, 반환없음
        }
       
    }
}

#Action 을 이용한 연습

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

namespace ConsoleApp8
{
    internal class App
    {
       
        public App()
        {
            Hero hero= new Hero();

            //hero.Move(() => { 
            //    Console.WriteLine("이동완료");
            //});
            //hero.Move메서드의 매개변수로 반환값이 없는 Action callback을 사용
            hero.onMoveComplete = () =>
            {
                Console.WriteLine("이동완료");
            };
            hero.Move(); //this.onMoveComplete 로 메서드 호출
            //이동중 ...
            //이동완료 순으로 출력

        }
        

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

namespace ConsoleApp8
{
    internal class Hero
    {
        public Action onMoveComplete; //맴버변수
        public Hero() 
        {

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

#Action을 이용한 연습 2

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

namespace ConsoleApp8
{
    internal class Item
    {
        public string Name
        {
            get;
            private set; //쓰기 전용 프로퍼티 생성
        }
        public Item(string name)
        {
            this.Name = name;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class Monster
    {
       public Action<Item> onDie; 
        public Monster()
        {

        }
        public void Die()
        {
            Console.WriteLine("몬스터가 죽었습니다.");
            Item item=new Item("장검");
            this.onDie(item);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp8
{
    internal class App
    {
       
        public App()
        {
            Monster mon=new Monster();
            mon.onDie = (item) =>
            {
                Console.WriteLine("아이템{0}을 드랍", item.Name);
            };
            mon.Die();
        }
        

    }
}