C#学习:Collection类的初体验

在C#语言中定义一个Collection类最简单的方法就是把System.Collection库中的CollectionBase类作为基础类。Collection类中包括了很多方法和属性,这里介绍一下Add方法、Remove方法、Count方法和Clear方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace myCollection
{
public class Collection :CollectionBase
{
public void Add(Object item)
{
InnerList.Add(item);
}
public void Remove(Object item)
{
InnerList.Remove(item);
}
public void Clear()
{
InnerList.Clear();
}
public int Count()
{
return InnerList.Count;
}
}
}

关于以上的实际应用,一般的资料上只介绍了简单的仅“姓名”队列的应用:

class Program
{
static void Main(string[] args)
{
Collection names = new Collection();
names.Add(“David”);
names.Add(“Bernic”);
names.Add(“Raymond”);
names.Add(“Clayton”);
foreach (Object name in names)
{
Console.WriteLine(name);
}
Console.WriteLine(“Number of names: {0}”, names.Count());
names.Remove(“Raymond”);
Console.WriteLine(“After remove Raymond,the number of names: {0}”, names.Count());
names.Clear();
Console.WriteLine(“Number of names: {0}”, names.Count());
Console.ReadKey();
}

然而,实际应用中,数据类型复杂。以下,是根据图灵计算机科学丛书《数据结构与算法(C#语言描述)》习题一所建立的复杂类型测试(不涉及题目的具体解答)。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using myCollection;
namespace tryCollectionClass
{
public class Students
{
private int studentID;
private string studentName;
public int ID
{
get
{
return studentID;
}
}
public string name
{
get
{
return studentName;
}
}
public Students(int id, string name)
{
this.studentID = id;
this.studentName = name;
}
}
class Program
{
static void Main(string[] args)
{
Collection studentCollection = new Collection();
Students stu1 = new Students(8503, “James”);
Students stu2 = new Students(8518, “Allbort”);
Students stu3 = new Students(8524, “YouGoFirst”);
Students stu4 = new Students(8537, “WeFinished”);
Students stu5 = new Students(8519, “ILikeIt”);
studentCollection.Add(stu1);
studentCollection.Add(stu2);
studentCollection.Add(stu3);
studentCollection.Add(stu4);
studentCollection.Add(stu5);
foreach (Students s in studentCollection)
{
Console.WriteLine(“{0} {1}”,s.name,s.ID);
}
Console.WriteLine();
Console.WriteLine(studentCollection.Count());
//Console.ReadKey();
studentCollection.Clear();
Console.WriteLine(“Clear”);
Console.WriteLine(studentCollection.Count());
Console.ReadKey();
}
}
}

[整理自网络]

此条目发表在other分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

您的电子邮箱地址不会被公开。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据