본문 바로가기
공부,일/C#

델리게이터 & 람다

by fromnothing1 2021. 6. 14.

델리게이트 = 함수 포인터 

: c # 에서 사용하는 함수 포인터 

 

간단 예제

 class Program
    {
        //delegaete type 생성 
        delegate void SMART();
        static void Main(string[] args)
        {
            SMART A;
            test1();
            A = test1;
            A();
        }
        static void test1()
        {
            Console.WriteLine("tset1");
        }
    }

심화 예제

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

namespace _210614_001
{
    class Program
    {
        //delegaete type 생성 
        delegate void SMART();
         class MessageMap
         {
            public string Name { get; set; }
            public SMART Handle { get; set; }
         }
        static void Main(string[] args) //MessageMap 기법 , 특정 메세지에 메소드 연결
        {
            MessageMap[] Map = new MessageMap[]
            {
                new MessageMap(){ Name = "일", Handle = test1},
                new MessageMap(){ Name = "이", Handle = test2},
                new MessageMap(){ Name = "삼", Handle = test3}
            };

            string Command;
            while (true)
            {
                Console.WriteLine("명령을 입력하세요(종료:e) : ");
                Command = Console.ReadLine();
                foreach (var item in Map)
                {
                    if (item.Name == Command)
                    {
                        item.Handle();
                    }
                }
                if (Command == "e")
                {
                    break;
                }
            }
        }
            static void Main2(string[] args)
        {
            SMART[] A = new SMART[3];
            A[0] = test1;
            A[1] = test2;
            A[2] = test3;
            foreach (var item in A)
            {
                item();
            }

        }
        static void Main1(string[] args)
        {
            SMART A;
            A = test1;
            A();
            A = test2;
            A();
            A = test3;
            A();
        }
        static void test1()
        {
            Console.WriteLine("tset1");
        }
        static void test2()
        {
            Console.WriteLine("tset2");
        }
        static void test3()
        {
            Console.WriteLine("tset3");
        }
    }
}

MessageMap 방식은 특정 문자열에 특정 메서드가 동작 되도록 하는 기법이다. 

 

 

 

매개 변수를 가지고 있는 함수의 delegate

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

namespace _2106104_002
{
    public delegate void SMART();
    public delegate int SMART2(int a);
    class Program
    {
      
        static void Main3(string[] args)// 반환값,매개변수 있는 메서드의 델리게이트
        {
            SMART2 A;
            A = test2;
            int iNum = A(100);
            Console.WriteLine(iNum);

            A = delegate (int a)
                {
                    Console.WriteLine("익명 혹은 무명 메서드 테스트");
                    return a + 2;
                };
            iNum = A(100);
            Console.WriteLine(iNum);
        }

        static void Main2(string[] args)// 반환값,매개변수 있는 메서드의 델리게이트
        {
            SMART2 A;
            A = test2;
            int iNum = A(100);
            Console.WriteLine(iNum);

        }
        static void Main1(string[] args)
        {
            SMART A;
            A = test1;
            A();

            A = delegate () // 이름이 없는 메서드
            {
                Console.WriteLine("임시로 만든 메서드");
            };

            A();
            A = delegate () // 이름이 없는 메서드
            {
                Console.WriteLine("익명로 만든 메서드");
            };

            A();

            A();

        }

        static void test1()
        {
            Console.WriteLine("test1");
        }
        static int test2(int iNum)
        {
            Console.WriteLine($"test2 : {iNum}");
            return iNum + 1;
        }
    }
}

 

 

람다식 

  static void Main(string[] args)// 반환값,매개변수 있는 메서드의 델리게이트
        {
            SMART A;
            A =  () =>
            {
                Console.WriteLine("람다식 메서드 ");
            };
        }

그냥 delegate 대신 => 쓰면 된다.

 static void Main(string[] args)// 반환값,매개변수 있는 메서드의 델리게이트
        {
            SMART2 A;
 

            A = (a)=> // type 을 적을 필요도 없다. 
            {
                Console.WriteLine("익명 혹은 무명 메서드 테스트");
                return a + 2;
            };
            int iNum = A(100);
            Console.WriteLine(iNum);
            
            A = (a) => { return a + 2;}; // 정말 간단하게 사용가능 
        }

람다 식은 type 마저도 안적어도 된다. 

 

'공부,일 > C#' 카테고리의 다른 글

파일 입력 생성 구현 코드  (0) 2021.10.01
210615_  (0) 2021.06.15
c# 에서 다차원 배열  (0) 2021.06.13
WinForms DataGridView  (0) 2021.06.11
Window Forms 리스트 박스 ,콤보 박스  (0) 2021.06.11

댓글