C# 용어 공부
C# 업캐스팅 다운캐스팅
프로핌
2023. 8. 10. 16:35
업캐스팅
부모 클래스의 타입을 변환할때 사용
부모 클래스의 포인터 변수로 자식 클래스의 객체를 가리킬때 사용
하지만 업캐스팅을 해도 부모 클래스는 부모 클래스의 정의했던 변수,메서드만 사용 가능하고 자식 클래스는 사용 불가능
그럼에도 쓰는 이유는 다형성을 이용한 코드 재사용
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp13
{
class Car
{
public int a = 5;
public virtual void Attack() { }
}
class Bar : Car
{
public int b = 2;
public override void Attack()
{
Console.WriteLine("아니 내가 공격한다");
}
public void Move()
{
Console.WriteLine("움직인다");
}
}
class Program
{
static void Main(string[] args)
{
Bar bar = new Bar();
Car car = (Car)bar; // 명시적 형 변환
Car car2 = new Bar(); // 암시적 형 변환
Console.WriteLine(car);
Console.WriteLine(car2);
}
}
}

분명 타입은 Bar 클래스 타입인데도

Bar 클래스의 정의된 변수를 호출할려 하면 오류가 발생
그럼에도 쓰는 이유는 다운캐스팅에서 볼수있다.
다운캐스팅
업캐스팅에서 사용하지 못했던 자식클래스의 정의되있는 변수,메서드를 사용하기위해
자식클래스 타입으로 다운캐스팅을 함
업캐스팅은 부모클래스 포인터 변수를 자식클래스 객체 형태타입을 변환해줬다면
다운캐스팅은 자식클래스 포인터 변수를 자식클래스 객체 형태타입을 변환해줌
이렇게 되면 자식클래스의 정의되있는 변수,메서드까지 사용가능함
하지만 여기서 주의할점은 타입이 동일해야 하며
무조건 명시적변환으로만 다운 캐스팅이 가능함
이유는 만약에 두개 이상의 자식클래스들이 부모클래스를 상속받은경우 암시적 변환으로 할경우 어떤 자식클래스 타입으로 변환한지 모르니깐 의도치 않은 오류가 생길 수 있다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp13
{
class Car
{
public int a = 5;
public virtual void Attack() { }
}
class Bar : Car
{
public int b = 2;
public override void Attack()
{
Console.WriteLine("아니 내가 공격한다");
}
public void Move()
{
Console.WriteLine("움직인다");
}
}
class Program
{
static void Main(string[] args)
{
Car car = new Bar();
Bar bar = (Bar)car;
Console.WriteLine(bar.a);
Console.WriteLine(bar.b);
Console.WriteLine(bar);
}
}
}
