본문 바로가기

C#/수업 내용

상속 연습 하기

-추가-

변형할수있는유닛 열거형식으로 정의 (드론,히드라)

변형 메서드에 반환값 추가

반환값을 변수에 넣어서 사용

메인메서드

using System;

class Program
{
    public enum eUnitType
    {
        Drone, Hydralisk
    }

    static void Main(string[] args)
    {
        ZergUnit larva1 = new Larva();
        Console.WriteLine();
        Larva larva = (Larva)larva1;
        Drone drone = (Drone)larva.Morph(eUnitType.Drone);
        drone.Gather();
        Console.WriteLine();
        ZergUnit larva2 = new Larva();
        Console.WriteLine();
        ZergUnit hydralisk1 = ((Larva)larva2).Morph(eUnitType.Hydralisk);
        Hydralisk hydralisk = (Hydralisk)hydralisk1;
        hydralisk.Attack();
    }
}

저그유닛 클래스 (부모클래스)

using System;

class ZergUnit
{
    //변수
    int hp;


    //생성자
    public ZergUnit()
    {
        Console.WriteLine("Unit클래스의 생성자");
    }


    //메서드
    void RecoveryHp()
    {

    }
}

라바 클래스

using System;

class Larva : ZergUnit
{
    //변수

    //생성자
    public Larva()
    {
        Console.WriteLine("Larva클래스의 생성자");
    }


    //메서드
    public ZergUnit Morph(Program.eUnitType unitType)
    {
        if (unitType == Program.eUnitType.Drone)
        {
            Console.WriteLine("{0}가 {1}으로 변태합니다.", this, unitType);
            return new Drone();
        }
        else if (unitType == Program.eUnitType.Hydralisk)
        {
            Console.WriteLine("{0}가 {1}으로 변태합니다.", this, unitType);
            return new Hydralisk();
        }
        else
        {
            return null;
        }
    }

}

드론 클래스

using System;

class Drone : ZergUnit
{
    //변수

    //생성자
    public Drone()
    {
        Console.WriteLine("Drone클래스의 생성자");
    }

    //메서드
    public void Gather()
    {
        Console.WriteLine("{0}이 자원을 채취합니다.", this);
    }
}

히드라 클래스

using System;

class Hydralisk : ZergUnit
{
    //변수

    //생성자
    public Hydralisk()
    {
        Console.WriteLine("Hydralisk클래스의 생성자");
    }

    //메서드
    public void Attack()
    {
        Console.WriteLine("{0}가 공격을 합니다.", this);
    }
}