Post

[C#] Lec 10 - 델리게이트, 이벤트

[C#] Lec 10 - 델리게이트, 이벤트

예외처리

Try Catch를 이용한 예외 처리

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static void Main() {
  try 
  {
    int [] arr = new int[]{1, 2, 3};
    for (int i = 0; i<4;i++) {
      Console.WriteLine(arr[i]);
    }
  }
  catch(Exception e) {
    Console.WriteLine($"exception : {e}");
  }
  Console.WriteLine("Finished");
}
  • catch 문을 여러개 중첩할 수 있음

임의로 예외 발생시키기

  • throw new Exception(“asdf”);
  • class MyException : Exception 으로 사용자 정의 Exception을 만들 수도 있음

델리게이트

  • delegate 반환형식 델리게이트명(매개변수);
1
2
3
4
5
6
7
8
9
10
delegate int Calc(int a, int b) ;

public static int Plus (int a, int b) { return a+b;}
public static int Minus (int a , int b ){ return a-b;}
static void Main(string[] args){
  int a = 4; b=5;
  Calc cal = new Calc(Plus);
  int c = cal(a,b);
  console.WriteLine(c);
}
  • delegate 선언부에서는 실제 입력받는 함수의 입력 매개변수와 출력 형식을 써주고, 이를 인스턴스화하여 사용할때에는 함수 자체의 이름을 매개변수로 넣어줌
  • 입출력 매개변수가 모두 같은 메소드만 델리게이트로 넣을 수 있음

delegate의 활용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
delegate int Compare(int a, int b);
static int AscendComparer(int a, int b) {
  if (a>b) {
    return 1;
  }
  else if (a==b) {
    return 0;
  }
  else {
    return -1;
  }
}
static int DescendComparer (int a, int b) {
  if (a>b) {
    return -1;
  }
  else if (a== b){
    return 0;
  }
  else {
    return 1;
  }
}
static Sort(int[]arr, Compare Comparer) {  // arr.Length = 4이면 총 3, 2, 1번 정렬.
//Ascend이든 Descend이든 3번 정렬후에 마지막에는 가장 큰/작은 수가 오므로 다음 iteration에서
// 맨 밑에 있는 item은 이미 정렬되있으므로 고려할 필요 없음
  for (int i = 0;i<arr.Length-1;i++) {
    for (int j = 0;j<arr.Length-(i+1);j++) {
      if (comparer(arr[j], arr[j+1])>0) {
        temp = arr[j+1];
        arr[j+1] = arr[j];
        arr[j]=temp;
      }
    }
  }
}
public static void Main() {
  int[] arr = {1, 9, 2, 8, 3};
  Sort(arr, Compare(AscendComparer)); //Descend로만 바꾸면됨
  for (int i = 0;i<arr.Length; i++){
    Console.WriteLine(arr[i]);
  }
}

Delegate chain

  • 델리게이트에 += 연산자를 이용하여 델리게이트 체인을 만들 수 있음
1
2
3
4
5
6
7
8
9
10
11
12
delegate void Del(string a);
public static void f1(string a) { Console.WriteLine(a);}
public static void f2(string a) { Console.WriteLine($"{a}!!");}

public static void Main(string[] args)
{
  Del del = new Del(f1);
  del("asdfasdf");
  del+= new Del(f2);
  del("asdfasdf");
}

익명 메소드

1
2
del+= delegate(string s) {Console.WirteLine($"익명 메소드: {s}");};
del+= s => {Console.WriteLine($"익명 메소드 2 {s}");};
  • 메소드의 이름을 만들지 않고 delegate 라는 이름으로 간단히 익명 메소드를 만들 수 있음.

이벤트 (Event)

  • 코드 뭉치를 매개변수로 넘기는 것이 중요
  • 델리게이트를 이용하여 이벤트를 선언할 수 있음.
  • 이벤트는 외부에서 직접 사용할 수 없음. (델리게이트는 외부 활용가능)
  • 객체의 상태 변화나 사건의 발생을 알리는 용도로 사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System;

namespace ConsoleApp2
{

  class Program
  {
    delegate void EventHandler(string message);
    class MyNotifier
    {
      public event EventHandler Event;
      public void Do(int number)
      {
        int temp = number % 10;
        if (temp != 0 && temp % 3 == 0)
        {
          Event($"{number} : 짝");
        }
      }
    }
    public static void MyHandler(string message)
    {
      Console.WriteLine(message);
    }
    public static void Main(string[] args)
    {
      MyNotifier notifier = new MyNotifier();
      notifier.Event += new EventHandler(MyHandler);
      for (int i = 1; i < 30; i++)
      {
        notifier.Do(i);
      }
    }
  }
}
  • 이벤트는 외부에서 쓸 수 없다 - > 클래스 밖으로 못나감?
1
2
3
4
5
6
7
8
9
10
11
delegate void Del(string a);
public static void f1(string a) { Console.WriteLine(a);}
public static void f2(string a) { Console.WriteLine($"{a}!!");}

public static void Main(string[] args)
{
	_Del del = new Del(f1);
	del("asdfasdf");
	del+= new Del(f2);
	del("asdfasdf");_
}
This post is licensed under CC BY 4.0 by the author.