유니티 C# : 익명 메서드와 람다식(Action, Func)

Se0ng_1l·2023년 8월 14일
0

일상 Unity

목록 보기
9/9
post-thumbnail

📌 주 목적 : 익명 메서드와 람다식을 이용하면 델리게이트에 메서드를 담는 코드를 상당 부분 줄여서 표현할 수 있다.

익명 메서드

정의 : 이름이 없는 메서드
다른 메서드를 넣어주지 않고 델리게이트의 선언과 정의를 동시에 수행한다.

OriginMethod

using UnityEngine;

public class OriginMethod : MonoBehaviour
{
    delegate int delegateCalc(int a, int b);

    private void Start()
    {
        delegateCalc cal = plus;
        cal(2, 4);
    }

    int plus(int a, int b)
    {
        return a + b;
    }
}

AnonymousMethod

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class AnonymousMethod : MonoBehaviour
{
    delegate int delegateCalc(int a, int b);

    private void Start()
    {
        delegateCalc cal = delegate(int i, int i1)
        {
            return i + i1;
        };

        Debug.Log(cal(9, 2));
    }
}

람다식(lambda expression)

익명 메서드로 간편하게 표현한 델리게이트를 더 간편하게 만들어보자
가능한 이유 : 컴파일러가 자동으로 유추하기 때문이다.
=> : 람다 연산자

📈 진화과정( 익명메서드 -> 람다식 )

익명메서드

delegateCalc cal = delegate(int a, int b)
{
	return a + b;
};

람다식 1(delegate 키워드, 매개변수의 타입 생략)

delegateCalc cal = (a, b) =>
{
	return a + b;
};

람다식 2(중괄호, return 키워드 추가 생략)

using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class LambdaExpression : MonoBehaviour
{
    delegate int delegateCalc(int a, int b);

    private void Start()
    {
        delegateCalc cal = (a, b) => a + b;

        Debug.Log(cal(9, 2));
    }
}

Action, Func

정의 :
익명 메서드와 람다식처럼 델리게이트에 메서드를 담아 전달하는 과정을 간단히하는 역할을 한다.
미리 정의된 델리게이트 변수

Action : 반환값이 없는 델리게이트
선언
   매개변수 없음 : Action act;
   매개변수 있음 : Action<매개변수 타입> act;

Func : 반환값이 있는 델리게이트
   선언 : Func<매개변수 타입, 매개변수 타입, 반환값의 타입> func;

Action (매개변수 없음)

using System;
using UnityEngine;

public class ActionNoPara : MonoBehaviour
{
    private void Start()
    {
        Action act = CallAction;
        act();
    }

    void CallAction()
    {
        Debug.Log("액션함수를 불러라");
    }
}

Action (매개변수 있음)

using System;
using UnityEngine;

public class ActionHavePara : MonoBehaviour
{
    private void Start()
    {
        Action<string> act = PrintAction;
        act("액션함수를 불러라");
    }

    void PrintAction(string str)
    {
        Debug.Log(str);
    }
}

Func

using System;
using UnityEngine;

public class FuncExample : MonoBehaviour
{
    private void Start()
    {
        Func<int, int, string> func = callFunc;
        func(7, 8);
    }

    string callFunc(int a, int b)
    {
        return "합은 : " + (a + b);
    }
}

⭐️Action + Func + Lambda

using System;
using UnityEngine;

public class ActionFuncLambda : MonoBehaviour
{
    private void Start()
    {
  		Action<string> act = (str) => Debug.log(str);
  		act("Hi");
        Func<int, int, string> func => (a + b) = "합은 : " + (a + b).ToString();
        Debug.log(3,7);
    }
}
profile
치타가 되고 싶은 취준생

0개의 댓글