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 |
'Language > C#' 카테고리의 다른 글
Enum.Parse (0) | 2018.10.27 |
---|---|
bool 변수를 property로 선언하면 최초로 무슨 값을 가질까? (0) | 2018.10.25 |
public, private, protected, internal keyword (0) | 2018.10.24 |
async await 사용시 조심해야 할 점 (0) | 2018.10.14 |
Object Oriented Robot Programming (0) | 2018.10.14 |