C#/수업 내용

[C#] class virtual override

JSH1 2021. 8. 27. 16:00
class Program
{
    public enum eUnitType
    {
        Larva,
        Drone,
        Hydra
    }

    static void Main(string[] args)
    {
        Unit larva1 = new Larva();

        Unit drone1 = larva1.Morph(eUnitType.Drone);
        drone1.Harvest();
        
        Unit larva2 = new Larva();
        Unit hydra1 = larva2.Morph(eUnitType.Hydra);

        hydra1.Attack();
    }
}
class Unit
{
    protected string name;

    //생성자
    public Unit()
    {
        Console.WriteLine("{0}: Unit 클래스의 생성자", this);
    }

    //멤버 메서드
    public virtual Unit Morph(Program.eUnitType unitType)
    {
        switch (unitType)
        {
            case Program.eUnitType.Drone:
                Console.WriteLine("{0}가 {1}으로 변태합니다.", this, unitType);
                return new Drone();

            case Program.eUnitType.Hydra:
                Console.WriteLine("{0}가 {1}로 변태합니다.", this, unitType);
                return new Hydra();

            default:
                return new Larva();
        }
    }

    public virtual void Harvest()
    {

    }

    public virtual void Attack()
    {

    }

    public void Move()
    {
        Console.WriteLine("{0}이 움직입니다.", this);
    }
}
class Larva : Unit
{
    //생성자
    public Larva()
    {
        Console.WriteLine("{0}: Larva 클래스의 생성자", this);
    }

    //멤버 메서드
    public override Unit Morph(Program.eUnitType unitType)
    {
        switch (unitType)
        {
            case Program.eUnitType.Drone:
                Console.WriteLine("{0}가 {1}으로 변태합니다.", this, unitType);
                return new Drone();

            case Program.eUnitType.Hydra:
                Console.WriteLine("{0}가 {1}로 변태합니다.", this, unitType);
                return new Hydra();

            default:
                return new Larva();
        }
    }
}
class Drone : Unit
{
    //생성자
    public Drone()
    {
        Console.WriteLine("{0}: Drone 클래스의 생성자", this);
    }

    //멤버 메서드
    public override void Harvest()
    {
        Console.WriteLine("{0}이 자원을 채취합니다.", this);
    }
}
class Hydra : Unit
{
    //생성자
    public Hydra()
    {
        Console.WriteLine("{0}: Hydra 클래스의 생성자", this);
    }

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


 

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

[C#] class 상속(parent, child), virtual, override  (0) 2021.08.29
[C#] 2021-08-27 오후  (0) 2021.08.27
[C#] 2021-08-26 오후  (0) 2021.08.26
[C#] 2021-08-26 오전  (0) 2021.08.26
[C#] 2021-08-25 오후  (0) 2021.08.25