본문 바로가기
c#/수업내용

2020.05.15 책 진도 449페이지까지

by Luna_O 2020. 5. 15.

ArrayList 다시 보기
예외처리하게 해보고 봐보기
delegate 알아야한다

콜백은 delegate의 인스턴스이고 델리게이트의 인스턴스에 매개변수로 메서드를 넣어준다

콜백이란 대리자는 델리게이트의 인스턴스이며, 인스턴스안에 메서드가 들어가있어서
콜백이 호출될때 델러게이트의 인스턴스 안에 있는 메서드가 호출이 된다는 것
대리자는 형식이고 인스턴스화 시킬수있으니까 객체이다 
page. 432 해보기, 440, 441, 444
익명메소드, 람다
이벤트

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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
 
delegate int MyDelete(int a, int b); // 1. 대리자 선언
delegate int calculate(int a, int b);
public class Test 
{
    public Test()
    {
        Debug.Log("Test");
        MyDelete callBack = new MyDelete(this.Plus); // 2. 대리자의 인스턴스 생성
        var result = callBack(34); // 3. 대리자 호출
        Debug.Log(result);
 
        MyDelete callBack2 = new MyDelete(Test.Minus);
        var result2 = callBack2(34);
        Debug.Log(result2);
 
        calculate calc;
        calc = delegate (int a, int b)  //익명 메소드
        {
            return a + b;
        };
    }
 
    public int Plus(int a, int b)
    {
        return a + b;
    }
 
    public static int Minus(int a, int b)
    {
        return a - b;
    }
}
cs
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public delegate void EventHandler(string massage);
 
public class Test1 
{
    public event EventHandler somethingHappened; //대리자 타입의 변수 선언
 
    public Test1()
    {
        this.somethingHappened += new EventHandler(Test1.MyHandler);  //객체를 생성하고 참조 메서드 연결
        this.somethingHappened += delegate (string msg)   //익명 메서드
        {
            Debug.Log(msg);
        };
 
        this.somethingHappened("Hello World");   //대리자 호출 =  2번 값나옴 메서드가 두개 참조 중이라서 먼저 참조한 순으로 호출됨
 
    }
    public static void MyHandler(string message)
    {
        Debug.Log(message);
    }
 
}
cs