본문 바로가기

.NET/C#

[C#] (delegate) Action & Func & Predicate

Action & Func & Predicate

  • delegate 를 더욱 간편하게 표현 하는 방법
  • 콜백 메커니즘, 이벤트 처리 및 메서드 인수로 전달 동작에 사용된다
  • 최대 16 인자를 가진 제네릭 표현
  • 람다식도 참조 할 수 있다.

Action

  • 반환 값이 없는 형태의 delegate 표현 void 
        static void Main(string[] args)
        {
            Action actionEcho = Echo;
            Action<int, int> actionAdd = Add;
            
            actionEcho();
            actionAdd(1, 2);
        }

        public static void Echo()
        {
            Console.WriteLine("Hello");
        }

        public static void Add(int x, int y)
        {
            Console.WriteLine(x + y);
        }
Action<string> action = (value) => Console.WriteLine(value);

Func

  • 반환값을 가지고 있는 형태의 delegate 표현
  • 마지막 제네릭 인자 값이 반환값이다.
        static void Main(string[] args)
        {
            Func<string> func1 = Func1;
            Func<int, int, string> func2 = Func2;
        }

        public static string Func1()
        {
            return "Hello";
        }

        public static string Func2(int x, int y)
        {
            return x + y + "";
        }
   Func<int, string> func = (x) => x + "";

Predicate

  • 반환값이 bool 형태의 delegate 표현

 

 


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  (0) 2023.08.17
[C#] ref & out  (0) 2023.08.04
[C#] C# 은 this 를 사용하지 않는가?  (0) 2023.07.29