본문 바로가기

C#

[C#] 업캐스팅과 다운캐스팅

반응형

https://see-ro-e.tistory.com/133

 

[C# 때려잡기] C# 강의 30. 다형성, 다운 캐스팅 업 캐스팅

기존에 내 캐릭터에 칼을 가지도록 하였다. class Weapon { public void Attack() { Console.WriteLine("무기로 공격!"); } } class Knife : Weapon { public void Attack() { Console.WriteLine("칼로 공격!"); } } class Gun : Weapon { } class

see-ro-e.tistory.com

업 캐스팅과 다운 캐스팅


업 캐스팅: 파생 클래스인 Cat, Dog, Bear 등을 부모 클래스인 Animal로 형 변환 해주는 것

다운캐스팅: 부모 클래스인 Animal을 파생 클래스인 Cat, Dog, Bear 등으로 로 형 변환 해주는 것

 

일반적으로 부모를 통하여 자식 객체에 접근하는 업 캐스팅은 허용되지만 자식으로 부모 객체를 가리키는 경우는 허용되지 않는다.

다운 캐스팅의 위험


class Animal
{
    public string Name;
    public string Color;
    protected int Age;

    public Animal(string Name, string Color)
    {
        this.Name = Name;
        this.Color = Color;
    }

    protected void Sing()
    {
        Console.WriteLine("Sing~");
    }
}

class Cat : Animal
{
    public static int Speed = 10;

    public Cat(): base("", "") { }

    public Cat(string Name, string Color): base(Name, Color) { }

    public Cat(string Name, string Color, int Age): base(Name, Color)
    {
        this.Age = Age;
    }


    public void Meow()
    {
        Console.WriteLine($"{this.Name}: 야옹");
    }
}

Cat 객체를 Animal에 담는 업 캐스팅

Animal cat = new Cat(); // 허용됨
cat.Sing(); // 가능
cat.Meow(); // 가능

Animal 객체를 Cat에 담는 다운 캐스팅

Cat animal = new Animal(); // 허용됨
animal.Sing(); // 가능
// animal.Meow(); // 불가능 - Animal 객체이기 때문

자식 객체의 크기와 부모 객체의 크기 비교


부모 객체에 자식 객체를 담는 이유는 다형성 때문이다.

오버라이드와 다형성

 

7장. 클래스: this 키워드, this() 생성자, 접근 한정자, static 변수, 구조체

주의) 생성자나 종료자 등 기본적인 것들은 생략하였습니다. 정적 필드와 메소드 선언, static using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestCon

bonjenny.tistory.com

 

반응형

'C#' 카테고리의 다른 글

[C#] DateTime 출력  (0) 2023.04.28
[C#] App.Config 활용  (0) 2023.04.28
[C#] 복잡한 리스트 중복제거  (0) 2023.04.20
[C#] 리스트 주요 함수 정리  (0) 2023.04.19
[C#] 문자열 메소드, 문자열 <-> 숫자 변환  (0) 2023.04.18