프로그래밍/C#

    [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 => 메소드(메소드의 호출 정보, 메소드 모양/주소)를 저장하는 타입 => ( ) ..

    [C#] 제너릭 제약 (Generic Constraint)

    [C#] 제너릭 제약 (Generic Constraint)

    1. 문제 using System; class Program { public static int Max(int a, int b) { return a < b ? b : a; } static void Main() { Console.WriteLine(Max(10, 20)); Console.WriteLine(Max("A", "B")); } } 위는 인자를 2개 받아 둘 중 더 큰 값을 리턴하는 Max함수를 만들어 사용하는 코드이다. 인자는 int타입만을 받고 있는데 10번째 라인과 같이 string타입도 비교를 하고 싶다고 해보자. string타입은 비교연산자를 사용할 순 없지만 CompareTo메소드를 통해 비교가 가능하다. CompareTo메소드는 앞이 크면 1, 작다면 -1, 같으면 0이 나오므로 0보다 ..

    [C#] 제너릭 (Generic)

    [C#] 제너릭 (Generic)

    1. 핵심 정리 using System; class Point { private int x; private int y; public Point(int xPos = 0, int yPos = 0) { x = xPos; y = yPos; } } class Program { static void Main() { Point pt = new Point(1, 1); // Point pt = new Point(1, 1.2); } } 위와 같은 코드가 있고 사용자들은 Point 객체를 만들어 사용하고 있는데 여기서 사용자가 Point pt = new Point(1, 1); 이 아닌 Point pt = new Point(1, 1.2); 와 같이 실수도 보내고 싶다라고 한다면 멤버를 double로 만들면 되긴 한다. 하지만..

    [C#] 인덱서 (Indexer)

    [C#] 인덱서 (Indexer)

    1. 핵심 정리 using System; class Sentence { private string[] words = null; public Sentence(string s) { words = s.Split(); } } class Program { public static void Main() { Sentence s = new Sentence("Dog is Animal"); s[0] = "Cat"; Console.WriteLine(s[0]); // Cat Console.WriteLine(s); // Cat is Animal } } ① 객체를 배열 처럼 사용할 수 있게 하는 문법 => C++에서 [ ] 연산자 재정의 => 속성(Property)와 유사한 문법 using System; class Sentenc..