K-digital traning/C#프로그래밍

대리자 연습 - Hero 이동

내꺼블로그 2023. 7. 27. 12:45

1.callback

 

(1)App.cs

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

namespace ConsoleApp1
{
    public class App
    {
        //생성자
        public App()
        {
            Hero hero = new Hero();
            
            Action action = () => {
                Console.WriteLine("영웅이 이동을 완료했습니다.");
            };
            
            hero.Move(action);
        } 
    }
}

or

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

namespace ConsoleApp1
{
    public class App
    {

        //생성자
        public App()
        {
            Hero hero = new Hero();
            
            hero.Move(() => {
                 Console.WriteLine("영웅이 이동을 완료했습니다.");
            });
        }
    }
}

 

 

 

(2)Hero.cs

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

namespace ConsoleApp1
{
    public class Hero
    {
        public Hero()
        {
        
        }

        public void Move(Action callback)
        {
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동완료");

            callback();
        }
    }
}

 

 

 

 

 

 

 

2.멤버 변수로 사용

(1) App.cs

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

namespace ConsoleApp1
{
    public class App
    {

        //생성자
        public App()
        {
            Hero hero = new Hero();
           
            hero.moveCompleteAction = () =>
            {
                Console.WriteLine("영웅이 이동을 완료했습니다.");
            };

            hero.Move();
        }
    }
}

 

 

 

 

(2)Hero.cs

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

namespace ConsoleApp1
{
    public class Hero
    {
        public Action moveCompleteAction;
        
        public Hero()
        {
            
        }
        
        public void Move()
        {
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동중...");
            Console.WriteLine("이동완료");

            moveCompleteAction();
        }
    }
}

 

 

 

 

결과