728x90
delegate void MyDelegate();
delegate void MyDelegate2(int i);
delegate void MyDelegate3(string str);
static void MyMethod() { Console.WriteLine("Hello"); }
static void MyMethod2(int i) { Console.WriteLine($"Hello {i}"); }
static void MyMethod3(MyDelegate myDelegate) => myDelegate();
static void MyMethod4(String str) { Console.WriteLine(str); }
static void MyMethod5(Func<string, int> myFunc, string str)
{
Console.WriteLine($"메시지의 크기는 {myFunc(str)}입니다.");
}
static int MyMethod6(string str){
return str.Length;
}
static void Main(string[] args)
{
MyDelegate myDelegate = new MyDelegate(MyMethod);
myDelegate();
MyDelegate myDelegate2 = MyMethod;
myDelegate2();
var myDelegate3 = MyMethod;
myDelegate3();
MyDelegate2 myDelegate21 = new MyDelegate2(MyMethod2);
myDelegate21(2);
var myDelegate4 = delegate ()
{
Console.WriteLine("Hello 4");
};
myDelegate4 += MyMethod;
myDelegate4();
MyMethod3(new MyDelegate(MyMethod));
Action<string> MyAction = new Action<string>(MyMethod4);
MyAction("Hello 5");
Action<string> MyAction2 = delegate (string str)
{
Console.WriteLine(str);
};
MyAction2("Hello 6");
Func<int, int, int> MyFunc = delegate (int x, int y) {
return x + y;
};
Console.WriteLine(MyFunc(7,8));
MyMethod5(new Func<string, int>(MyMethod6), "Hello 7");
}
델리게이트명 변수명 = new 델리게이트명(메소드명);
델리게이트명 변수명 = 메소드명;
델리게이트는 메소드 포인터
좌측이 델리게이트면 우측에 델리게이트는 생략가능
MyDelegate myDelegate2 = MyMethod;
메소드에 델리게이트를 매개변수를 가질 수 있음
MyMethod3(MyDelegate myDelegate)
MyMethod5(Func<string, int> myFunc, string str)
델리게이트로 무명메소드 호출
myDelegate4 = delegate(){}
델리게이트에 기존 메소드에 다른 메소드를 추가
myDelegate4 += MyMethod
Action 대리자: 반환값이 없는 메서드를 대신 호출
Func 대리자: 매개변수와 반환값이 있는 메서드를 대신 호출
Predicate 대리자: 매개변수에 대한 bool 값을 반환하는 메서드를 대신 호출
MyMethod3(MyMethod);
var myDelegate4 = () => Console.WriteLine("Hello 4");
Action<string> MyAction2 = (str) => Console.WriteLine(str);
Action<string> MyAction2 = Console.WriteLine;
Func<int, int, int> MyFunc = (x, y) => x + y;
MyMethod5(MyMethod6, "Hello 7");
람다식으로 줄일 수 있음
매개변수 자리에 들어갈때도 델리게이트는 생략가능
→ 메소드에 매개변수가 메소드로 들어가있는 걸로 보임
※delegate
명사 (집단의 의사를 대표하는) 대표(자)
동사 (권한·업무 등을) 위임하다
동사 (대표를) 뽑다[선정하다]
728x90
'Programming > C#' 카테고리의 다른 글
C# dynamic csharp (0) | 2025.05.12 |
---|---|
C# 튜플 tuple csharp (0) | 2025.05.12 |
C# 웹소켓 WebSocket 주요 메서드 정리 (0) | 2025.02.28 |
C# 비동기 프로그래밍 예제 Asynchronous programming Task void async await (0) | 2025.02.28 |
람다 표현식 (0) | 2025.02.14 |