C#中的collection类
一:定义Collection类
在C#语言中定义一个Collection类最简单的方法就是把System.Collection库中的CollectionBase类作为基础类。
二:实现Collection类
Collection类中包括了很多方法和属性,这里介绍一下Add方法、Remove方法、Count方法和Clear方法。
代码如下
show sourceview sourceprint?01 public class collection : CollectionBase
02 {
03 public void Add(object item)
04 {
05 InnerList.Add(item); //添加
06 }
07 public void Remove(object item)
08 {
09 InnerList.Remove(item); //删除
10 }
11 public int Count()
12 {
13 return InnerList.Count; //返回元素个数
14 }
15 public void Clear()
16 {
17 InnerList.Clear(); //全部清除
18 }
三:实例化一个类
本例实例化了两个类,分别是submittedTexts(试卷存放的类)和outForChecking(试卷取出后存放的类)
代码如下
show sourceview sourceprint?1 collection submittedTexts = new collection();
2 collection outForChecking = new collection();
四:例子
这是一个模拟试卷提交的一个程序。功能如下:(1)录入某姓名和试卷编号,把试卷插入到submittedTexts集合中;
(2)录入姓名,从submittedTexts中删除相应试卷,并把试卷插入到outForChecking集合中;
(3)录入姓名,从outForChecking中删除试卷,并放回到submittedTexts中;
(4)按退出按钮,从outForChecking中删除所有试卷,并全部插入到submittedTexts中。
程序界面如下:
1、用get方法获取textBox中的值
代码如下
show sourceview sourceprint?01 public string Nametext
02 {
03 get
04 {
05 return textBox1.Text;
06 }
07 }
08 public string Numtext
09 {
10 get
11 {
12 return textBox2.Text;
13 }
2、各按钮的功能实现
代码如下
show sourceview sourceprint?01 提交试卷
02 int Numtext2 = int.Parse(Numtext);
03 submittedTexts.Add(Nametext);
04 MessageBox.Show("试卷已经提交");
05
06 取出试卷(用collection类中的Contains判断元素是否在集合中)
07 if (submittedTexts.Contains(Nametext))
08 {
09 submittedTexts.Remove(Nametext);
10 outForChecking.Add(Nametext);
11 MessageBox.Show("试卷已经取出");
12 }
13 else
14 MessageBox.Show("没有这份试卷");
15
16 试卷总数
17 label4.Text =submittedTexts.Count().ToString();
18
19 放回试卷
20 if (outForChecking.Contains(Nametext))
21 {
22 outForChecking.Remove(Nametext);
23 submittedTexts.Add(Nametext);
24 MessageBox.Show("试卷已经放回");
25 }
26 else
27 MessageBox.Show("没有这份试卷");
28 }
29
30 全部清除
31 foreach (string item in outForChecking)
32 {
33 submittedTexts.Add(item);
34 }
35 outForChecking.Clear();
Collection类中的各种方法和属性,请参考aspx">http://msdn.microsoft.com/zh-cn/library/ms132397.aspx
补充:软件开发 , C# ,