본문 바로가기
PROGRAMING📚/C#📑

C# 델리게이트가 생성되는 방식(Action,Func,Delegate,Lambda)

별찌루 2023. 5. 18.
728x90
반응형

Delegate

 

대리자는 메소드의 주소를 참조해 메소드를  대신 호출해주는 기법이라고 말할 수 있다. 이런 대리자를 선언해주기 위해서 대리자(델리게이트) 선언을 해주어야한다. 방법은 다음과 같고 매개 변수를 안에 넣어 줄 수 도 있다.

 

한정자 delegate 반환타입 대리자이름 ( 매개변수)

 public delegate void TestDelegates();

 

그리고 델리게이트를 사용하기 위해서 필드를 하나 만들어 주어야한다. 필드는 대리자의 한정자(private) 이름(TestDelegates) 필드 이름(testDeleateFunction) 이런 식으로 대리자를 선언해준다.

 

    private TestDelegates testDeleateFunction;

 

 

Delegate를 사용하는 방법으로 위에 필드 안에 출력 하고 싶은 함수 MyFirstDelegateFunction()라는 함수를 만들어서 넣어 줬다. 호출하는 방법은 델리게이트로 만들어 주었던 필드를 호출해주면 된다.

 

1. 필드안에 매소드 참조하고 호출 하는 방법

   testDeleateFunction = MyFirstDelegateFunction;
   testDeleateFunction(); //대리자 호출,함수 실행
   
    private void MyFirstDelegateFunction()
    {
        Debug.Log("MyFirstDelegateFunction");
    }
public class Delegates : MonoBehaviour
{
    public delegate void TestDelegates();
    private TestDelegates testDeleateFunction;
    private void Start()
    {
        testDeleateFunction = MyFirstDelegateFunction;
        testDeleateFunction();//대리자 호출,함수 실행
        testDeleateFunction = MyScecondDelegateFunction;
        testDeleateFunction();//대리자 호출,함수 실행
    }
    //   public delegate void TestDelegates();에 매개변수가 따로 없기 때문에 
    private void MyFirstDelegateFunction()
    {
        Debug.Log("MyFirstDelegateFunction");
    }
    private void MyScecondDelegateFunction()
    {
        Debug.Log("MySecondDelegateFuction");
    }
}

 

델리케이트 안에 두 가지 다른 동작을 넣어서 멀티캐스트로 사용이 가능하다.

위의 코드를 대입연산자를 사용해서 하나의 델리게이트(대리자) 가 두 개의 메소드를 참조해서 출력해줄 수 있다.

 

2. (+=/-=)대입 연산자를 사용해서 필드안에 메소드 참조(추가/삭제) 하는 방법

    	testDeleateFunction = MyFirstDelegateFunction;
        testDeleateFunction += MyScecondDelegateFunction;
        testDeleateFunction();//대리자 호출,함수 실행

 

3.반환하는 값이 없는 함수 한줄로 호출 하는 방법

   private void Start()
    {
        testDeleateFunction += new TestDelegates(MyFirstDelegateFunction);
        testDeleateFunction += new TestDelegates(MyScecondDelegateFunction);
        testDeleateFunction();//대리자 호출,함수 실행
    }

 

4. 코드 블록 내부에 함수를 생성하고  간단하게 출력하는 방법

 testDeleateFunction += delegate () { Debug.Log("출력하고 싶은 내용"); };

    private void Start()
    {
        testDeleateFunction += delegate () { Debug.Log("MyFirstDelegateFunction"); };
        testDeleateFunction += delegate () { Debug.Log("MySecondDelegateFuction"); };

        testDeleateFunction();
    }

 

5. 람다식(()=>)을 이용해서 간단하게 출력하는 방법

testDeleateFunction += ()=> { Debug.Log("MyFirstDelegateFunction"); };
testDeleateFunction += () => { MyScecondDelegateFunction(); };

 

*Delegate에 매개변수가 존재 할 경우 생성 된 필드에도 동일한 매개변수가 들어가야 한다.

생성된 필드에도 동일한 매개 변수를 넣어주면 오류가 사라지는 것을  확인 할 수 있다.

매개변수가 존재하는 코드도 람다식으로 표현 해줄수 있다.

testDeleate_countFunction += (int i) => { i = 5; Debug.Log("i : "+i); };
testDeleate_countFunction += (int i) => { Deleagate_count(6); };
testDeleate_countFunction(count);

 

 

 

Action 

 

Action을 사용하기 위해서는 using System;을 선언 해주어야 한다.

앞에서는 Delegate를 정의했지만 이번에는 Action이라는 것을 정의해서 사용한다.

 

형태
public void Action<입력 매개변수>(매개변수);

<참조방법 예시>

//매개변수가 없는 경우
public Action FirstAction;
//매개변수가 있는 경우
public Action<int, float> SecondAction;
//매개변수가 없는 경우
FirstAction = () => { FirstAcitonFunction(); };
//매개변수가 있는 경우
SecondAction = (int i, float f) => { Debug.Log("SceondAction"); };

 

Func

 

반환값을 가진 메서드를 참조하는 대리자(델리게이트)라서 반환성을 반드시 지정해주어야 사용이 가능하다.

 

형태
public 반환형 Func<입력 매개변수,반환형> (매개변수);

<참조 방법 예시>

    private Func<bool> FirstFunc;
    private Func<int, bool> SecondFunc;

 

FirstFunc =() => false;
SecondFunc = (int i) => { return i < 5f; };

 

Action 대리자와 Func 대리자는 같은 기능을 하지만 둘의 차이점은 반환타입으로 나누어진다. 반환 타입이 없는 경우에는 Action 대리자를 사용하고 반환타입이 존재할 경우에는 Func 대리자를 사용한다.

 

 

728x90
반응형

댓글