- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 212字
- 2021-07-02 15:29:19
Downcasting
Now, we will talk about downcasting, which means going from, for example, a parent type to a child type. Enter the following between a set of curly braces below this line:
sampLabel.Text += ((Square)lst[0]).Perimeter();
Now, beneath the closed curly brace after the preceding line, enter the following:
else if(lst[0] is Rectangle)
Then, you can call the following code; so, copy the sampLabel.Text... line and paste it between a set of curly braces:
sampLabel.Text += ((Rectangle)lst[0]).Perimeter();
Be sure to change Square to Rectangle, so that it gets cast down to a rectangle, and then the Perimeter function on the rectangle will be called. When you hover your mouse over Perimeter in the preceding two lines, the popups show string Square.Perimeter() and string Square.Perimeter(), respectively. If you removed (Rectangle) from the preceding line and hovered your mouse over Perimeter, the popup will show string Quad.Perimeter(). Do you understand? This is why I have the cast: because it changes the way the functions are recognized.
This is downcasting from a parent to a child class. So, when we talk about bulk actions, you cannot cast to a parent class, perform a bulk action like a sort, or if you want to add refinements called child classes and child class objects, then you can downcast.
- HornetQ Messaging Developer’s Guide
- Mastering Ember.js
- HTML5+CSS3基礎開發教程(第2版)
- CKA/CKAD應試教程:從Docker到Kubernetes完全攻略
- C語言課程設計
- Mastering ROS for Robotics Programming
- RESTful Java Web Services(Second Edition)
- C++20高級編程
- Nagios Core Administration Cookbook(Second Edition)
- OpenCV 3計算機視覺:Python語言實現(原書第2版)
- RESTful Web Clients:基于超媒體的可復用客戶端
- Learning Bootstrap 4(Second Edition)
- 計算機系統解密:從理解計算機到編寫高效代碼
- 一步一步學Spring Boot:微服務項目實戰(第2版)
- Learning NHibernate 4