使用CollectionBase自定义强类型集合类

Intro:
CollectionBase实际上就是MS提供给我们的一个简化实现了IList接口的抽象基类。利用它可以使我们更加方便的自定义强类型的集合类
通过使用Reflector可以发现,CollectionBase这个抽象基类,实际上继承了IList,ICollection和IEnumerable三个接口,并且显式地实现了IList接口的Add()和Remove()等方法,另外提供了一个受保护的属性IList List以方便我们使用。

public   abstract   class  CollectionBase : IList, ICollection, IEnumerable
{
    
// Methods
    int IList.Add(object value);
    
void IList.Remove(object value);

    
// Properties
    protected IList List get; }
}

Content:
1)首先定义一个Person类如下:
     public   class  Person
    
{
        
protected string name;

        
public Person()
        
{
            
this.name = "No name..";
        }


        
public Person(string name)
        
{
            
this.name = name;
        }


        
public override string ToString()
        
{
            
return "The name is " + this.name;
        }

    }

2)添加一个集合类PersonList,继承CollectionBase这个基类,并使用其中已经实现的IList接口中的两个方法
     public   class  PersonList : System.Collections.CollectionBase
    
{
        
public void Add(Person person)
        
{
            
// 调用父类的IList.Remove()方法
            List.Add(person);
        }


        
public void Remove(Person person)
        
{
            
// 调用父类的IList.Remove()方法
            List.Remove(person);
        }


        
// 为集合类添加索引器
        public Person this[int index]
        
{
            
get
            
{
                
return (Person)List[index];
            }

            
set
            
{
                List[index] 
= value;
            }

        }

    }

3)入口函数中调用上面定义的PersonList
         static   void  Main( string [] args)
        
{
            PersonList psCollection 
= new PersonList();
            psCollection.Add(
new Person("jack"));
            psCollection.Add(
new Person("rose"));

            
// 遍历集合
            Console.WriteLine("遍历集合:");
            
foreach (Person p in psCollection)
            
{
                Console.WriteLine(p.ToString());
            }


            
// 使用索引器
            Console.WriteLine("使用索引器:");
            Console.WriteLine( psCollection[
0].ToString() );
            Console.WriteLine( psCollection[
1].ToString() );

            Console.ReadKey();
        }

结果输出:


总结:通过 CollectionBase可以很方便的自定义一个强类型的集合类,而不用手写一个继承IList的集合类了。

转载于:https://www.cnblogs.com/cnxcfeng/archive/2008/05/10/1191745.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值