C#中的collection类

348 篇文章 0 订阅

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();
Collection类中的各种方法和属性,请参考 http://msdn.microsoft.com/zh-cn/library/ms132397.aspx

分类:  C#
1
3
« 上一篇: WP7音乐播放机

» 下一篇:用C#中的Timing类测试时间


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值