: 이름 없는 함수
(1) delegate 키워드 사용 ( delegate 뒤에 이름이 없음 = 익명 함수 )
Action sayHello = delegate
{
Console.WriteLine("Hello!");
};
sayHello(); // 출력: Hello!
(2) 람다식 사용(더 간결)
Action sayHello = () => Console.WriteLine("Hello!");
sayHello(); // 출력: Hello!
기본 구조
// 일반 함수
int Double(int x) { return x * 2; }
// 람다 식
Func<int, int> doubleFunc = x => x * 2;
익명함수 + 람다 식
using UnityEngine;
using UnityEngine.UI;
public class StudyLambda : MonoBehaviour
{
public delegate void MyDelegate(string s);
public MyDelegate myDelegate;
public Button button;
void Start()
{
// 버튼에 1개의 기능을 등록하는 방법
button.onClick.AddListener(ButtonEvent);
// button.onClick.AddListener(OnLog("Hello")); // 사용 X
// 익명함수로 여러 기능을 등록하는 방법
button.onClick.AddListener(delegate
{
ButtonEvent();
OnLog("Lambda");
});
// 람다식으로 1개의 기능을 등록하는 방법
button.onClick.AddListener(() => OnLog("Hello"));
// 람다식으로 여러 기능을 등록하는 방법
button.onClick.AddListener(() =>
{
ButtonEvent();
OnLog("Lambda");
});
}
private void ButtonEvent()
{
Debug.Log("Button Event");
}
private void OnLog(string msg)
{
Debug.Log(msg);
}
}