C#/수업 내용

Cal 연습문제 (대리자)

Bueong_E 2023. 1. 11. 12:51
반응형
SMALL

 App 클래스

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study10
{
    class App
    {
        //생성자 
        public App()
        {
            Calculator cal = new Calculator();
            int sum = cal.Plus(1, 2);
            Console.WriteLine("sum: {0}", sum);
            //(불가능, Minus는 static 메서드)
            //static 메서드는 형식으로 접근 
            //int result = cal.Minus(5, 2);
            int result = Calculator.Minus(5, 2);
            Console.WriteLine("result: {0}", result);

            //3. 대리자 변수 정의 
            Calculator.MyDel myDel;

            //4. 대리자 인스턴스화 (메서드)하고 변수에 할당 
            myDel = new Calculator.MyDel(cal.Plus);

            //5. callback 호출 (대리자 호출)
            //연결된 메서드 지금은 누구? Plus 메서드 
            result = myDel(1, 2);    //Plus 메서드 실행 
            Console.WriteLine(result);


            Calculator.MyDel myDel2;
            myDel2 = new Calculator.MyDel(Calculator.Minus);    //statck 메서드 
            //콜백 (메서드)호출(대리자의 메서드 호출)
            result = myDel2(5, 2);
            Console.WriteLine(result);
        }

    }
}

 Calculator Class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study10
{
    class Calculator
    {
        //2. 대리자 형식 정의 (Delegate상속받은 MyDel 형식)
        public delegate int MyDel(int x, int y);

        //맴버 변수 

        //생성자 
        public Calculator()
        { 

        }

        //맴버 메서드 정의 
        //1. 대리자에 연결할 메서드 정의 
        public int Plus(int a, int b)
        {
            return a + b;
        }

        public static int Minus(int a, int b)
        {
            return a - b;
        }
    }
}

 

반응형
LIST