728x90
delegate 는 이미 c#에 잘 정의 되어있어 Func나 Action을 주로사용한다
Func와 Action을 사용하기 전에 어떻게 구성되어있는지 먼저 확인하자
class MainClass {
delegate Return Test<T, Return>(T num);
static void TestProgram(Test<int, int> test){
test(1);
}
static void Main() {
//일회성 함수로 람다식을 사용하였다
Test<int, int> test = (int num) => {Console.WriteLine($"Finish{num}"); return 0;};
TestProgram(test);
}
}
위와같이 정의한 Test delegate는 미리 정의 되어있는 Func로 아래와 같이 바꿀 수 있다
class MainClass {
static void TestProgram(Func<int, int> test){
test(1);
}
static void Main() {
Func<int, int> test = (int num) => {Console.WriteLine($"Finish{num}"); return 0;};
TestProgram(test);
}
}
이와 같이 Func는 최대 16개의 매개변수를 가질 수 있고 마지막에 리턴형식을 지정해 주면 된다
만약 리턴값이 없으면 어떨까? 그때 사용하는 delegate가 Action이다
class MainClass {
static void TestProgram(Action<int> test){
test(1);
}
static void Main() {
Action<int> test = (int num) => {Console.WriteLine($"Finish{num}");};
TestProgram(test);
}
}
C#에서 직접 Func<void> 같은 형식으로 void를 넣을수 없으므로 Action을 사용한
728x90
'언어 정리 > c#' 카테고리의 다른 글
C# - StringBulider (0) | 2023.12.29 |
---|---|
c# - lambda 간단한 사용예제 (0) | 2023.11.26 |
c# - delegate 사용법 (2) | 2023.11.26 |
c# 코드시간 측정 방법 (0) | 2023.02.16 |
c# - delegate (0) | 2023.01.11 |