본문 바로가기
프로그램/C#

[C#][기초] Action, Func 은 언제 어떻게 사용하나?

by 요셉Han 2020. 4. 21.

출처: https://ko.wikipedia.org/wiki/C_%EC%83%A4%ED%94%84

 

2020/04/17 - [프로그램언어/C#] - [C#][기초] Delegate/Event 는 언제 어떻게 사용하나?

 

[C#][기초] Delegate/Event 는 언제 어떻게 사용하나?

A Class 가 B Class 를 사용하고 있을 때, A Class 는 B Class 의 Public Variable/Method 를 마음껏 사용할 수 있지만, B Class 는 A Class 에게 하고 싶은 말이 아무리 많아도 직접적으로 전달할 수가 없다. 이..

joseph-han.tistory.com

위의 글에서 Delegate 와 Event 를 사용하는 방법에 대해 알아봤다.

이번에는 .net framework 에서 제공하는 Action 과 Func 에 대해서 알아보려 한다. Action 과 Func 는 Delegate/Event 를 조금 더 간단히 사용할 수 있도록 .net framework 에서 제공해주는 미리 선언된 Delegate 변수이다.

Action/Func 는 .net framework 3.5 이상부터 사용이 가능하다.

 

반환값이 필요없는 Event 는 Action<T>

반환값이 필요없는 Event 를 사용하고자 한다면 Action 을 사용하면 된다.

Action<T> 에서 T 의 자리에 n 개의 type 을 입력하면 해당 type 들이 전송 가능한 파라메터로 자동 인식된다.

사용하는 방법은 본 페이지 제일 하단의 샘플 코드를 참고하자.

MSDN 에는 .net framework 4.8 을 기준으로 최대 16개의 파라메터까지 지원이 가능한 것으로 소개되었다.

https://docs.microsoft.com/ko-kr/dotnet/api/system.action-16?view=netframework-4.8

 

Action<t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16> 대리자 (System)</t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16>

 

매개 변수가 16개이고 값을 반환하지 않는 메서드를 캡슐화합니다.Encapsulates a method that has 16 paramet

docs.microsoft.com

 

반환값이 필요한 Event 는 Func<T>

반환값이 필요한 Event 를 사용해야 할 때는 Action<T> 가 아니라 Func<T> 를 사용하면 된다.

Func<T> 도 n 개의 파라메터를 전달할 수 있다. 기본적은 사용법은 Action<T> 와 동일하다.

단, 마지막 파라메터는 반환값의 type 임을 유의하자!!!

역시 MSDN 에는 .net framework 4.8 을 기준으로 최대 16개의 파라메터까지 지원이 가능한 것으로 소개되었다.

https://docs.microsoft.com/ko-kr/dotnet/api/system.func-1?view=netframework-4.8

 

Func 대리자 (System)

 

매개 변수가 없고 TResult 매개 변수에 지정된 형식의 값을 반환하는 메서드를 캡슐화합니다.

docs.microsoft.com

 

샘플 코드
 internal class ActionFuncSample
    {
        //Action => 반환값이 없음. N 개의 파라메터 전달 가능
        internal event Action<int, bool> ActionEvent = null;
        //Func => 반환값이 있음. N 개의 파라메터 전달 가능. 마지막으로 설정한 type 이 반환 type
        //아래의 예제에서는 마지막 bool 이 반환 type 임
        internal event Func<int, bool, bool> FuncEvent = null;

        internal void SendActionEvent()
        {
            if (null != ActionEvent) ActionEvent(14, false);
        }

        internal void SendFuncEvent()
        {
            if(null != FuncEvent)
            {
                if (FuncEvent(14, false)) Console.WriteLine("The result of FuncEvent is true.");
                else Console.WriteLine("The result of FuncEvent is false.");
            }
        }
    }

    internal class ActionFuncConsumer
    {
        internal ActionFuncSample afSample;

        internal ActionFuncConsumer()
        {
            afSample = new ActionFuncSample();
            afSample.ActionEvent += AfSample_ActionEvent;
            afSample.FuncEvent += AfSample_FuncEvent;
        }

        private bool AfSample_FuncEvent(int arg1, bool arg2)
        {
            //이벤트 처리
            //여기서는 1000까지의 랜덤수를 2로 나누어서 떨어지면 true, 아니면 false
            bool result = arg1 % 2 == 0 ? true : false;

            //결과 반환
            return result;
        }

        private void AfSample_ActionEvent(int arg1, bool arg2)
        {
            //이벤트 처리
            //반환값 없음
        }
    }

 

 

댓글