Upcasting and Downcasting

2018. 10. 24. 07:18 from Language/C#

What is upcasting and Downcasting


Upcasting converts an object of specialized type to a more general type.
Downcasting converts an object from general type to a more specialized type.

specialized type = child class / general type = mother class

이거를 specialized는 석사, general은 대학생 이라고 생각하면 쉽다. 대학생이 석사 수업을 받으면 Upcasting, 석사가 대학생 수업을 받으면 Downcasting이 되는 것이다.

example:

1
2
3
4
5
6
7
8
9
10
testDevice Mother1 = new testDevice();
testDevice Mother2 = new testDevice();
 
testDeviceMPlus Child1 = new testDeviceMPlus();
testDeviceMPlus Child2 = new testDeviceMPlus();
 
Mother1 = Child1; // Upcasting. allowed.
Child2 = Mother2; // Downcasting. Illegal. Discovered at compile time.
Child2 = (testDeviceMPlus)Mother2; // Downcasting. Illegal. Discovered at run time.
Child2 = (testDeviceMPlus)Mother1;  // Downcasting. allowed. Mother1 already refers to a testDeviceMPlus
cs



Actual use

Device배열로 자식 class를 전부 넣어놓는다(Upcasting). 이후에 자식 method를 사용할 일이 있으면 Downcasting을 통해서 사용하면된다.


example:

1
2
3
4
5
6
7
8
9
10
11
12
// device
private Device[] Devices;
private CylinderController Cylinder;
                
private void DeviceInit()
{
    Devices = new Device[(int)DeviceList.Size] {
        new CylinderController() { DeviceName = "Cylinder" }    // upcasting
    };
 
    Cylinder = (CylinderController)Devices[(int)DeviceList.Cylinder];   // downcasting
}
cs

Posted by 나무길 :