본문 바로가기

C#/수업 내용

대리자 연습4

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

namespace HelloWorld
{
    class App
    {
        //1.대리자 선언
        public delegate void Del(Weapon weapon);

        //생성자
        public App()
        {
            Blacksmith blacksmith = new Blacksmith();
            //3.변수선언하고 넣기 (연결)
            Del handler = CreateWeaponHandler;

            blacksmith.CreateWeapon("장검", this.CreateWeaponHandler);
        }

        //2. 연결할 메서드 정의
        void CreateWeaponHandler(Weapon weapon)
        {
            Console.WriteLine("Created weapon: {0}", weapon.name);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Weapon
    {
        public string name;

        //생성자
        public Weapon(string name)
        {
            this.name = name;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Blacksmith
    {
        App.Del del;

        //생성자
        public Blacksmith()
        {
            
        }

        public void CreateWeapon(string name, App.Del callback)
        {
            Weapon weapon = new Weapon(name);
            callback(weapon);   //4. 대리자를 호출한다
        }
    }
}

'C# > 수업 내용' 카테고리의 다른 글

대리자연습6 고블린 (오류)  (0) 2021.12.24
대리자 연습 5  (0) 2021.12.24
대리자 연습 3  (0) 2021.12.24
대리자 연습 2  (0) 2021.12.24
1-2주차 복습 (꿈의나라)  (0) 2021.12.24