[C#] Delegate, Func, Action, 람다 함수

송칭·2024년 9월 26일
0

Delegate

C#에서 메서드 참조를 저장하고 호출할 수 있는 타입으로 특정 함수를 변수처럼 다루기 위해 사용하는 방법이다.

public delegate int MathOperation(int x, int y);

public class Calculator
{
	public int Add(int a, int b)
	{
		return a + b;
	}

	public int Multiply(int a, int b)
	{
		return a * b;
	}

}

class Program
{
    static void Main(string[] args)
    {
    	Calculator calc = new Calculator();
        
        MathOperation add = calc.Add;
        MathOperation multiply = calc.Multiply;
        
        Console.WriteLine(add(10, 20));       // 출력: 30
        Console.WriteLine(multiply(10, 20));  // 출력: 200
    }
}

Func / Action

Func와 Action은 delegate의 한 종류로 Func의 경우 반환값이 있는, Action은 반환값이 없는 메서드를 참조할 때 사용한다.

Func<>에는 2개 이상의 타입을 정의하는데 그 중 맨 뒤는 반환값의 타입을 정의한다.

public class Calculator
{
	public int Add(int a, int b)
	{
		return a + b;
	}
}

class Program
{
    static void Main(string[] args)
    {
    	Calculator calc = new Calculator();
		Func<int, int, int> add = calc.Add;
        
        Console.WriteLine(add(10, 20));       // 출력: 30
    }
}

Action은 반환형이 void인 메서드만 참조할 수 있다.

class Program
{
	static void PrintMessage(string message)
    {
        Console.WriteLine(message);
    }
    
    static void Main(string[] args)
    {
        Action<string> printMessage = PrintMessage;
        
        printMessage("Hello, World!");  // 출력: Hello, World!
    } 
}

람다함수

람다 함수(Lambda Expression)는 C#에서 익명 메서드를 간결하게 작성할 수 있는 방법이다.

람다 함수의 형식
(파라미터, ... , 파라미터) => 처리할 함수

람다 함수는 기본적으로 delegate 타입으로 변환되는데 덕분에 람다 함수를 사용하면 별도의 메서드 선언 없이 delegate를 직접 정의할 수 있다.

public delegate int MathOperation(int x, int y);

class Program
{
    static void Main(string[] args)
    {
        MathOperation add = (x, y) => x + y;
        MathOperation multiply = (x, y) => x * y;
        
        Console.WriteLine(add(10, 20));       // 출력: 30
        Console.WriteLine(multiply(10, 20));  // 출력: 200
    }
}
profile
게임 클라이언트

0개의 댓글