자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[C#] 13장 C# 람다식과 Func

728x90

 

1. 람다식 (Lambda Expression)

람다식(Lambda)는 익명 메서드(이름 없는 메서드)를 간결하게 표현하는 방식입니다.

(매개변수) => 식 or { 문장들 }
class Lamda
{
    static void Main()
    {
        // Normal Method
        int Square(int x)
        {
            return x * x;
        }

            // Lamda Method
            Func<int, int> square = x => x * x;

        Console.WriteLine(square(5));
    }

}

✅ 2. Func 

Func는 반환 값이 있는 람다식/메서드를 담는 제네릭 델리게이트(delegate)로 최대 16개의 입력 매개변수를 받을 수 있고, 마지막 타입 매개변수는 반환 타입입니다.

Func<T1, T2, ..., TResult>
class FuncDel
{
    static void Main()
    {
        Func<int, int, int> add = (a, b) => a + b;
        Console.WriteLine(add);

        Func<string, int> strLength = s => s.Length;
        Console.WriteLine(strLength("Hello, World!")); // 13
    }
}

✅ 3. Action

Action(액션)은 반환값이 없는 델리게이트로 최대 16개의 입력 매개변수를 가질 수 있습니다.

Action<T1, T2, ...>
class Action
{
    static void Main()
    {
        Action<string> print = msg => Console.WriteLine(msg);
        print("Hello!");

        Action<int, int> multiply = (a, b) => Console.WriteLine(a * b);
        multiply(4, 5); // 20
    }
}

✅ 4. Func vs Action 차이

구분 Func Action
반환값 있음 없음
매개변수 0~16개 0~16개
사용 예 계산 결과 반환 단순 실행, 출력, 로그

✅ 5. 실무 예제

class LinQ
{
    static void Main()
    {
        var numbers = new List<int> { 1, 2, 3, 4, 5 };

        // Func 사용
        var squares = numbers.Select(x => x * x);
        foreach (var n in squares)
            Console.WriteLine(n);

        // Action
        numbers.ForEach(n => Console.WriteLine($"값: {n}"));
    }
}

 

 

GitHub - Koras02/project

Contribute to Koras02/project development by creating an account on GitHub.

github.com

 

728x90
LIST

'게임 모딩 > C#' 카테고리의 다른 글

[C#] 15장 제네릭 심화  (0) 2025.09.05
[C#] 14장 LINQ 기본 -> 고급쿼리  (2) 2025.08.31
[C#] 12장 C# 델리게이트와 이벤트  (0) 2025.08.20
[C#] 11장. C# 예외 처리  (1) 2025.08.18
[C#] 10장. C# 패턴일치  (0) 2025.02.26