• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
①只螃蟹?条腿™...
.NET世界是如此精彩,而我们要做的就是:Thinking More..
博客园    首页    新随笔       管理    订阅  订阅
使用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的集合类了。
posted on 2008-05-10 23:36  A.feng..  阅读(801)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3