Love

To the world you may be one person,but to one person you may be the world.

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Extends Collection and Action collection

Posted on 2009-02-23 17:05  timmy.tian  阅读(212)  评论(0)    收藏  举报

 


/////Extends Collection

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

class ConverterCollection<T> : Collection<T>
{
    
private Converter<T, T> convert;

    
public ConverterCollection(Converter<T, T> convert)
    {
        
this.convert = convert;
    }

    
protected override void InsertItem(int index, T item)
    {
        
base.InsertItem(index, convert(item));
    }
}

public class MainClass
{
    
public static void Main()
    {
        ConverterCollection
<string> c = new ConverterCollection<string>(
            
delegate(string s) { return s.ToUpper(); });
        c.Add(
"Hello");
        c.Add(
"World!");

        
foreach (string s in c)
            Console.WriteLine(s);
    }
}

/////// Action Collection
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

class ActionCollection<T> : Collection<T>
{
    
private Action<T> action;

    
public ActionCollection(Action<T> action)
    {
        
this.action = action;
    }

    
protected override void InsertItem(int index, T item)
    {
        action(item);
        
base.InsertItem(index, item);
    }
}


public class MainClass
{
    
public static void Main()
    {
        ActionCollection
<string> ac = new ActionCollection<string>(Console.WriteLine);
        ac.Add(
"console");
        
    }
}