3、在C#中实现面向对象的概念
目标
? ? ?
编写一个队列类的C#程序。 this关键字的使用。
构造函数的重载和普通函数的重载。
第一部分 指导(50分钟)
练习1:队列类的应用程序
问题
在数据结构中已经学习了队列,请用C#编写一个类实现队列的功能,并编写一个测试类测试该队列的功能。(参考.Net的类库中已经封装好了的队列类:System.Collections.Queue,可以将自己做好的类,和它进行比较) 指导教师讲解问题说明
队列是限定所有的插入操作在表的一端进行,而删除操作在表的另一端进行的线性表,具有先进先出的特性。确定该队列中存储的值类型为整数类型。 分析
一个队列有入排和出排动作,可以编写两个函数分别命名为EnQueue和DeQueue;还应该有一个属性Length:判断队列中的元素个数;一个打印的函数Print:将队列中所有的值进行打印输出。 推荐步骤:
(1)新建一个名为“QueueWithCSharp”的基于控制台应用程序的项目。 (2)添加一个类,名为:Queue,添加以下代码。
using System; using System.Collections.Generic; using System.Text; namespace QueueWithCSharp { public class Node { public int data; public Node prior, next; public Node() { prior = null; next = null; data = 0; } } public class Queue { Node head, rear; int length; public int Length { get { return length; } } public Queue() { // // TODO: 在此处添加构造函数逻辑 // head = rear = null; length = 0; } public void EnQueue(int data) // 追加 { if (rear == null) { rear = new Node(); head = rear; rear.data = data; length++; } else { rear.next = new Node(); rear.next.data = data; length++; rear = rear.next; } } public int DeQueue() //删除 { if (length <= 0) { rear = head = null; Console.WriteLine(\队列中没有元素\ return 0; } int data = head.data; head = head.next; length--; return data; } public void Print() //打印 { string str = \ Node current = head; while (current != null) { if (current == head) { str += current.data.ToString(); } else { str += \ } current = current.next; }// end while current Console.WriteLine(str); } } } (3)在Program.cs类中调用Queue类,代码如下:
using System; using System.Collections.Generic; using System.Text; namespace QueueWithCSharp { class Program { static void Main(string[] args) { //定义一个 队列类 Queue demQueue = new Queue(); //数据入排 demQueue.EnQueue(10); demQueue.EnQueue(19); demQueue.EnQueue(50); demQueue.EnQueue(99); //数据出排 demQueue.DeQueue(); //打印队列中的数据 demQueue.Print(); } } } (4)生成项目。
(5)选择“调试” →“开始执行(不调试)”选项来执行此应用程序,输出结果如图1.1所示。
图1.1 练习1的输出结果
练习2:this关键字的使用
问题
this关键字的使用 指导教师讲解问题说明
this引用有三种典型的使用方式。第一种方式是限定被参数掩藏的实例变量;
public void Function1(int i) { This.i=i; } 第二种用法是把当前对象作为参数传给另一个方法;
public void Method1() { OtherClass obj= new OtherClass(); obj.Method2(this); } 第三种方法与索引器有关。
public Class this[string title] { get { foreach(?) ? return class; } } 分析
定义一个汽车类,这个类有多个构造函数,因为这些构造函数之间有部分功能是重叠的,所以可以进行相互调用。在进行构造函数的互相调用时,this关键字调用参数最匹配的那个构造函数。 推荐步骤:
(1)使用Visual Studio.NET 2005新建一个基于控制台的项目“CallConstructor”。 (2)将“Program.cs”类文件重命名为“Car.cs”。 (3)将以下代码添加到“Car.cs”中。
using System; using System.Collections.Generic; using System.Text; namespace CallConstructor { public class Car { int petalCount = 0; string s = \ Car(int petalCount) { this.petalCount = petalCount; //this的第一种用法 Console.WriteLine(\ } Car(String s, int petals) : this(petals) //this关键字调用参数最匹配的那个构造函数 { this.s = s; Console.WriteLine(\ } Car(): this(\ { Console.WriteLine(\ } static void Main(string[] args) { Car x = new Car();