포스트

Unity C# Lambda

Lambda

익명 메소드와 람다의 차이점

  • 익명 메소드:
    • 익명 메소드는 C# 2.0에서 도입
    • 델리게이트를 더 간단하게 만들 수 있는 방법을 제공.
    • 하지만 익명 메소드는 여전히 메소드의 본체를 {} 안에 작성해야 함.
  • 람다 표현식:
    • C# 3.0부터 도입
    • 람다 표현식은 익명 메소드를 더욱 간결하게 만듦.
    • 람다 표현식은 => 연산자를 사용하여 더 짧은 구문으로 같은 기능을 수행할 수 있음.

익명 메소드

  • 이름이 없는 메소드.
  • 일회성 메소드에 사용

익명 메소드 정의

1
2
3
4
델리게이트 변수 = delegate(매개변수 목록)
{
    // 실행할 코드
};

다음의 두 코드는 실행 결과가 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate void TestDelegate();

    private void Start()
    {
        TestDelegate testDele;
        testDele = TestFunction;
        
        testDele.Invoke();
    }

    void TestFunction()
    {
        Debug.Log("asdf");
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate void TestDelegate();

    private void Start()
    {
        TestDelegate testDele;
        testDele = delegate()
        {
            Debug.Log("asdf");
        };
        
        testDele.Invoke();
    }
}

예제1 - 매개변수와 반환이 있는 형태

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate int TestDelegate(int num1, int num2);

    private void Start()
    {
        TestDelegate testDele;

        testDele = delegate(int num1, int num2)
        {
            return num1 + num2;
        };

                
        
        int result = testDele.Invoke(3, 5);
        Debug.Log(result);
    }
}

람다 Lambda

람다식의 장점

  • 간결성:
    • 람다 표현식은 코드를 간결하게 만들어 줌.
    • 특히 LINQ 쿼리나 이벤트 핸들러 같은 곳에서 코드의 양을 상당히 줄일 수 있음.
  • 가독성 향상:
    • 람다 표현식은 코드의 목적을 더 명확하게 표현할 수 있도록 도와줌.

람다식의 단점

  • 디버깅의 어려움:
    • 람다 표현식은 디버깅할 때 복잡성을 증가시킬 수 있음.
    • 특히 람다가 여러 줄에 걸쳐 있는 경우, 디버거에서 각 줄을 개별적으로 추적하기 어려울 수 있음.
  • 스코프 및 캡처 문제:
    • 람다 표현식은 주변 스코프의 변수를 “캡처”할 수 있음.
    • 이는 의도하지 않은 부작용을 일으킬 수 있으므로 주의가 필요.

람다식 정의

1
2
3
4
5
6
7
8
9
10
델리게이트 변수 = (매개변수 목록) => ;

// 혹은

델리게이트 변수 = (매개변수 목록) => 
                                {
                                        문장1;
                                        문장2;
                                        문장3;
                                };

다음의 두 코드는 실행 결과가 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate void TestDelegate();

    private void Start()
    {
        TestDelegate testDele;
        testDele = delegate()
        {
            Debug.Log("asdf");
        };
        
        testDele.Invoke();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate void TestDelegate();

    private void Start()
    {
        TestDelegate testDele;
        testDele = () => Debug.Log("asdf");

        testDele.Invoke();
    }
}

다음의 두 코드도 실행 결과가 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate int TestDelegate(int num1, int num2);

    private void Start()
    {
        TestDelegate testDele;

        testDele = delegate(int num1, int num2)
        {
            return num1 + num2;
        };

                
        
        int result = testDele.Invoke(3, 5);
        Debug.Log(result);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate int TestDelegate(int num1, int num2);

    private void Start()
    {
        TestDelegate testDele;
        testDele = (num1, num2) => num1 + num2;

        int result = testDele.Invoke(3,5);
        Debug.Log(result);
    }
}

람다식과 델리게이트 체인

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using UnityEngine;

public class Lambda : MonoBehaviour
{
    delegate void TestDelegate();

    private void Start()
    {
        TestDelegate testDele;
        testDele = () => Debug.Log("Test1");
        testDele += () => Debug.Log("Test2");    // (1)
        testDele -= () => Debug.Log("Test2");    // (2)

        testDele.Invoke();
    }
}
  • 델리게이트 체인 관리:
    • 람다식을 사용하여 델리게이트 체인을 관리할 때는 동일한 람다식을 +==로 추가하거나 제거하더라도 서로 다른 인스턴스로 간주됨.
    • 이는 람다 표현식이 매번 새로운 델리게이트 인스턴스를 생성하기 때문.
    • 따라서 람다 표현식을 사용하여 델리게이트 체인을 관리할 때는 이 점을 유의해야 함.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.