- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 331字
- 2021-07-02 15:29:19
Upcasting
Notice that I've written new Square. This is upcasting. Here, this involves converting the object on the right-hand side, because it's derived from its Quad. On the left-hand side, you can make a Quad namespace and put an object that is of a derived type on the right side; so, we'll call this one Square and then enter a side length of 4.
Next, enter the following directly below this line:
Quad rect = new Rectangle("Rectangle", 2, 5);
Again, we put a Quad namespace on the left-hand side, and this time we called it rect. We give it the name Rectangle, and then we put in two sides of lengths 2 and 5.
Now, you can store this in a list, for example, which you can sort. Imagine if you had many of these, you would need a way to sort this information. So now, go to the top of this file, and enter the following beneath using System:
using System.Collections.Generic;
Next, under the Quad rect... line, enter the following:
List<Quad> lst = new List<Quad>(new Quad[] { sqr, rect, rect2, sqr1 });
We'll call this list new List<Quad>, and to initialize a list you can always use an array. To do this, type new Quad and then initialize it with sqr and rect. This is how you can always initialize a list within an array.
Then, to sort the list, enter the following directly below this line:
lst.Sort();
So, this makes sense now. It doesn't give an error. Imagine if you didn't have IComparable<Quad> at the top of the GenInterface class. This sort would not work. If you cut IComparable<Quad>, and then take the CompareTo method out, you will have problems. So, for our purposes, we now have a way of sorting these Quads classes.
For the last stage, start by entering the following below the Sort line:
if(lst[0] is Square)
So, is is a new keyword. You can use it to check whether something is of a certain type.
- 自然語言處理實戰:預訓練模型應用及其產品化
- Design Principles for Process:driven Architectures Using Oracle BPM and SOA Suite 12c
- Power Up Your PowToon Studio Project
- Spring Boot+Spring Cloud+Vue+Element項目實戰:手把手教你開發權限管理系統
- Python爬蟲開發與項目實戰
- Python金融數據分析
- C語言程序設計實踐教程
- Apache Karaf Cookbook
- 從學徒到高手:汽車電路識圖、故障檢測與維修技能全圖解
- PostgreSQL Replication(Second Edition)
- 嚴密系統設計:方法、趨勢與挑戰
- Java EE 8 Application Development
- 計算機應用基礎教程(Windows 7+Office 2010)
- PHP 7從零基礎到項目實戰
- Zabbix Performance Tuning