본문 바로가기

.NET/C#

[C#] delegate

delegate

  • 메소드를 값으로 표현하기 위한 문법
  • C++의 함수 포인터 
delegate int DelegateFunc(int x, int y);

public int Add(int x, int y)
{
	return x + y;
}
DelegateFunc delFunc;

// 여러가지 방법의 메서드 참조, 아래의 방법중 하나를 선택
delFunc = new DelegateFunc(Add);
delFunc = Add; // C# 2.0 이상
delFunc += Add;

아래의 2 구문은 당연하게도 동일한 결과를 리턴한다.

Add(3, 4); // 원본 메소드
delFunc(3, 4); // 델리게이트

delegate chaining

  • delegate 에 여러 개의 메소드를 참조 할 수 있다.
  • -= 를 통해 메소드를 제거할 수 있다.
delegate void DelCalc(int x, int y);

static void Add(int x, int y){ Console.WriteLine(x + y); }
static void Sub(int x, int y){ Console.WriteLine(x - y); }
static void Mul(int x, int y){ Console.WriteLine(x * y); }
static void Div(int x, int y){ Console.WriteLine(x / y); }

static void Main(string[] args)
{
	DelCalc calc = Add;
    calc += Sub;
    calc += Mul;
    calc += Div;
    
    calc(10, 5);
    
    calc -= Div;
    
    calc(10, 5);
}
// 결과
15
5
50
2

15
5
50

delegate callback 

  • 메소드의 반환값, 메소드의 인자, 클래스의 멤버로 델리게이트를 정의할 수 있다.
  • 메소드의 반환값, 메소드의 인자, 클래스의 멤버로 메소드를 정의 할 수 있다.
  • C# 은 1급 함수가 지원되는 언어 (first-class function) 
        public delegate int DelegateFunc(int x, int y);


        static void Main(string[] args)
        {
            TestFunc(new DelegateFunc(Add)); // 30
        }

        public static int Add(int x, int y)
        {
            return x + y;
        }

        public static void TestFunc(DelegateFunc delFunc) {
            int x = 10;
            int y = 20;
            int result = delFunc(x, y);
            Console.WriteLine(result);
        }

delegate 익명함수

        public delegate int DelegateFunc(int x, int y);


        static void Main(string[] args)
        {
            DelegateFunc delFunc = delegate (int x, int y) {
                return x + y;
        	};

            Console.WriteLine(delFunc(10, 20));
            Console.ReadLine();
        }

lambda, 람다

  • 화살표 모양의 간단한 표현식
  • 함수를 일일이 선언하지 않고 간편하게 메소드를 표현하여 가독성을 높힌다.
public delegate int DelegateFunc(int x, int y);

static void Main(string[] args)
{
	DelegateFunc delFunc = (x, y) => x + y;
}
      public delegate int DelegateFunc(int x, int y);


        static void Main(string[] args)
        {
            TestFunc((x, y) => x + y); // 30
            TestFunc((x, y) => x - y); // -10
        }

        public static void TestFunc(DelegateFunc delFunc) {
            int x = 10;
            int y = 20;
            int result = delFunc(x, y);
            Console.WriteLine(result);
        }

There might be incorrect information or outdated content.

'.NET > C#' 카테고리의 다른 글

[C#] Parse 사용시 발생하는 이슈 🔥  (0) 2023.11.23
[C#] First, FirstOrDefault  (1) 2023.09.21
[C#] (delegate) Action & Func & Predicate  (0) 2023.08.18
[C#] ref & out  (0) 2023.08.04
[C#] C# 은 this 를 사용하지 않는가?  (0) 2023.07.29