c# delegate

    [C#] 람다 표현식 (Lambda Expression)

    [C#] 람다 표현식 (Lambda Expression)

    1. 핵심 정리 using System; class Program { public static void foo(Func f) { int s = f(1, 2); Console.WriteLine(s); } static void Main(string[] args) { foo( ? ); } } Main에서 foo함수의 인자로 메소드를 받는데 메소드의 이름이 아닌 구현부를 넣을 수 있다. 이름을 제외한 인자~구현부까지 넣으면 되는데 형태는 아래와 같다. using System; class Program { public static void foo(Func f) { int s = f(1, 2); Console.WriteLine(s); } static void Main(string[] args) { foo(Add);..

    [C#] Action, Func

    [C#] Action, Func

    1. Action using System; class Program { public static void Foo1(int arg1) { } public static void Foo2(int arg1, int arg2) { } static void Main() { ? f1 = Foo1; ? f2 = Foo2; } } Main에서 Foo1, Foo2 메소드의 정보를 담고 싶다. 그렇다면 앞선 내용대로 delegate를 사용하면 된다. using System; delegate void Foo1(int arg1); delegate void Foo2(int arg1, int arg2); class Program { public static void Foo1(int arg1) { } public static voi..

    [C#] Delegate Chain

    [C#] Delegate Chain

    1. Delegate Combine using System; class Test { public static int Method1() { Console.WriteLine("Method1"); return 1; } public static int Method2() { Console.WriteLine("Method2"); return 2; } public static int Method3() { Console.WriteLine("Method3"); return 3; } public static int Method4() { Console.WriteLine("Method4"); return 4; } } delegate int FUNC(); class Program { public static void Main(..

    [C#] Delegate Example

    [C#] Delegate Example

    1. 예제 using System; class Program { public static void Swap(ref int a, ref int b) { int temp = a; a = b; b = temp; } public static void Sort(int[] arr) { int sz = arr.GetLength(0); for(int i = 0; i arr[j]) Swap(ref arr[i], ref arr[j]); } } } static void Main() { int[] x = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}; Sort(x); foreach(int n in x) ..

    [C#] Delegate (2)

    [C#] Delegate (2)

    1. Delegate에 메소드를 등록하는 방법 using System; delegate void FUNC(int arg); class Test { public static void static_method(int arg) { } public void instance_method(int arg) { } } class Program { public static void static_method(int arg) { } public void instance_method(int arg) { } public static void Main() { FUNC f1 = Test.static_method; // FUNC f2 = Program.static_method; // ok FUNC f2 = static_method;..

    [C#] Delegate (1)

    [C#] Delegate (1)

    1. 핵심 정리 using System; delegate void FUNC(int arg); class Program { static void Main() { int n = 10; double d = 3.4; string s = "hello"; // ? f = foo; FUNC f = foo; } public static void foo(int arg) { Console.WriteLine($"foo : {arg}"); } } 정수형 데이터 타입을 담는 int 실수형 데이터 타입을 담는 double 문자열 데이터 타입을 담는 string 그렇다면 11번째 라인과 같이 함수를 담는 데이터 타입을 무엇일까? ① Delegate => 메소드(메소드의 호출 정보, 메소드 모양/주소)를 저장하는 타입 => ( ) ..