The sample code for the structure in section 1.2.1 in chapter 1 of this book (see the web site: http://book.51cto.com/art/200905/123578.htm) may need to be modified, because the strange thing is that property writing is useless. Change the tostring () override method and initials () method:
public override string ToString(){ return (String.Format("{0} {1} {2}", firstName, middleName, lastName));}public string Initials(){ return (String.Format("{0} {1} {2}", firstName.Substring(0, 1), middleName.Substring(0, 1), lastName.Substring(0, 1)));}
In the sample code snippet above, change fname to firstname, mname to middlename, and lname to lastname. After such a program is modified, its attributes are called directly in the structure, and the attribute values are assigned through the constructor of the new structure.
Next, in Section 1.3.3, the count method of the program should be changed from the method to the attribute, rather than the method.
public int Count{ get { return InnerList.Count; }}
Sample code snippet in the count Section
Console.WriteLine("Number of names: " + names.Count);names.Remove("David");Console.WriteLine("Number of names: " + names.Count);names.Clear();Console.WriteLine("Number of names: " + names.Count);
Sample code snippet in the main () method section
The output result of count is: 4, 3, 0. After such a program is modified, the collection class is actually implemented.
Exercise Question 1.7 in section 2nd: add the insert, contains, indexof, and removeat methods to the Collection class.
public void Insert(int index, object item){ InnerList.Insert(index, item);}public bool Contains(object item){ return InnerList.Contains(item);}public int IndexOf(object item){ return InnerList.IndexOf(item);}public int IndexOf(object item, int startIndex){ return InnerList.IndexOf(item, startIndex);}public int IndexOf(object item, int startIndex, int count){ return InnerList.IndexOf(item, startIndex, count);}public void RemoveAt(int index){ InnerList.RemoveAt(index);}
Exercise 3rd: Use the timing class to compare the performance when integers are added to the Collection class and the arraylist class respectively.
using System;class TestDemo{ static void BuildArray(Collection arr) { for (int i = 0; i <= 1000000; i++) { arr.Add(i); } } static void DisplayNums(Collection arr) { foreach(int i in arr) { Console.Write(i + " "); } } static void Main(string[] args) { Collection nums = new Collection(); BuildArray(nums); Timing obj = new Timing(); obj.startTime(); DisplayNums(nums); obj.stopTime(); Console.WriteLine("Time: " + obj.Result.TotalSeconds); }}
The above program running result is:
This is the Program Implementation of the Collection class. The Program Implementation of the arraylist class is the same as that of the class. This post is omitted.