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