[CS] 메서드를 매개변수로 전달

Sireal·2022년 5월 9일
0

C#

목록 보기
21/30

델리게이트(대리자) 라는 친구를 앞서 본적있다.

얘를 응용하면 한 클래스의 메소드를 함수의 매개변수로 던져줄 수 있다.

방법은 총 세가지이다.
1. Func 대리자 : 0~16개 입력 매개변수를 가진, void형을 제외한 반환타입 가진 매서드만 참조.
2. Action 대리자 : 0~16개 입력 매개변수를 가진, void형인 매서드만 참조함.
3. Predicate 대리자 : 무조건 1개의 입력 매개변수를 가진, bool형 메서드만 참조함.

Func 대리자

public delegate returType Func<in inputType, out returnType>(InputType arg);

  • in : in 뒤에는 매개변수 자료형을 정의함.
  • out : out 뒤에는 매서드의 반환타입을 정의함.
  • InputType : 매서드의 매개변수
// 함수에 매개변수가 있을 때. (<In Out> 다 적음)
public static string AddFunc(int a, int b)
{
	return (a+b).ToString();
}

static void Main(string[] args)
{
	Func<int, int, string> funcDelegate = AddFunc;
    Console.WriteLine(funcDelegate(10,20)); // 30
}
// 함수에 매개변수가 없을 때 (<Out>만 적음)
public static string PrintFunc()
{
	return "Hello";
}

static void Main(string[] args)
{
	Func<string> funcDelegate = PrintFunc;
    Console.WriteLine(funcDelegate()); // Hello
}

Action 대리자

Func 대리자와 똑같이 생겼는데, 반환형이 없는 메서드만 취급함

public static void PrintSubFnc(int a, int b)
{
	Console.WriteLine((a-b).ToString());
}
// Func도 이렇게 매개변수로 쓸 수 있음.
public static void PrintFunc(Action<int, int> Func, int a, int b)
{
	Func(a,b); 
}

static void Main(string[] args)
{
	PrintFunc(PrintAddFunc, 100, 200);
    PrintFunc(200, 200);
}

Predicate 대리자

Func, Action 대리자와 같은데, 반환형이 무조건 bool이며, 매개변수는 딱 한개만 취급하는 대리자임.

public static bool BoolFunc(int age)
{
	if(age > 19)
    	return true;
    else
    	return false;
}

public static void PrintFunc(Predicate<int> Func, int age)
{
	if(Func(age))
    	Console.WriteLine("20살 이상");
    else
    	Console.WriteLine("20살 미만");
}

static void Main(string[] args)
{
	PrintFunc(BoolFunc, 30);
    PrintFunc(BoolFunc, 10);
}

따라적은 글

profile
🚄계속 앞으로🚄

0개의 댓글

관련 채용 정보