欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

C#集合之自定义集合类

时间:2022-08-30 09:29:11|栏目:.NET代码|点击:

一、非泛型方式,继承自CollectionBase

public class MyClass
{
    public static void Main()
    {
        StringCollection myStringCol = new StringCollection();
        myStringCol.Add("a");
        myStringCol.Add("b");
        Console.Write(myStringCol[0]);
        foreach (string myAnimal in myStringCol)
        {
            Console.Write(myAnimal);
        }
        Console.ReadKey();
    }
}
//自定义集合类
public class StringCollection : CollectionBase
{
    public void Add(string newAnimal)
    {
        List.Add(newAnimal);
    }

    public void Remove(string newAnimal)
    {
        List.Remove(newAnimal);
    }

    public StringCollection() { }

    public string this[int animalIndex]
    {
        get { return (string)List[animalIndex]; }
        set { List[animalIndex] = value; }
    }
}

二、泛型方式,继承自Collection<T>

下面的代码示例演示如何从构造类型的派生集合类Collection<T>泛型类,以及如何重写受保护InsertItem, RemoveItem, ClearItems,和SetItem方法,以提供自定义行为Add, Insert, Remove,和Clear方法,并设置Item[Int32]属性。
此示例中提供的自定义行为是Changed每个受保护方法结束时引发的通知事件。
Dinosaurs类继承Collection<string>,并定义Changed事件,使用DinosaursChangedEventArgs类用于事件信息和使用枚举标识的更改种类。

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

public class Dinosaurs : Collection<string>
{
    public event EventHandler<DinosaursChangedEventArgs> Changed;

    protected override void InsertItem(int index, string newItem)
    {
        base.InsertItem(index, newItem);

        EventHandler<DinosaursChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new DinosaursChangedEventArgs(
                ChangeType.Added, newItem, null));
        }
    }

    protected override void SetItem(int index, string newItem)
    {
        string replaced = Items[index];
        base.SetItem(index, newItem);

        EventHandler<DinosaursChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new DinosaursChangedEventArgs(
                ChangeType.Replaced, replaced, newItem));
        }
    }

    protected override void RemoveItem(int index)
    {
        string removedItem = Items[index];
        base.RemoveItem(index);

        EventHandler<DinosaursChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new DinosaursChangedEventArgs(
                ChangeType.Removed, removedItem, null));
        }
    }

    protected override void ClearItems()
    {
        base.ClearItems();

        EventHandler<DinosaursChangedEventArgs> temp = Changed;
        if (temp != null)
        {
            temp(this, new DinosaursChangedEventArgs(
                ChangeType.Cleared, null, null));
        }
    }
}

// Event argument for the Changed event.
//
public class DinosaursChangedEventArgs : EventArgs
{
    public readonly string ChangedItem;
    public readonly ChangeType ChangeType;
    public readonly string ReplacedWith;

    public DinosaursChangedEventArgs(ChangeType change, string item, 
        string replacement)
    {
        ChangeType = change;
        ChangedItem = item;
        ReplacedWith = replacement;
    }
}

public enum ChangeType
{
    Added, 
    Removed, 
    Replaced, 
    Cleared
};

public class Demo
{
    public static void Main()
    {
        Dinosaurs dinosaurs = new Dinosaurs();

        dinosaurs.Changed += ChangedHandler; 

        dinosaurs.Add("Psitticosaurus");
        dinosaurs.Add("Caudipteryx");
        dinosaurs.Add("Compsognathus");
        dinosaurs.Add("Muttaburrasaurus");

        Display(dinosaurs);
    
        Console.WriteLine("\nIndexOf(\"Muttaburrasaurus\"): {0}", 
        dinosaurs.IndexOf("Muttaburrasaurus"));

        Console.WriteLine("\nContains(\"Caudipteryx\"): {0}", 
        dinosaurs.Contains("Caudipteryx"));

        Console.WriteLine("\nInsert(2, \"Nanotyrannus\")");
        dinosaurs.Insert(2, "Nanotyrannus");

        Console.WriteLine("\ndinosaurs[2]: {0}", dinosaurs[2]);

        Console.WriteLine("\ndinosaurs[2] = \"Microraptor\"");
        dinosaurs[2] = "Microraptor";

        Console.WriteLine("\nRemove(\"Microraptor\")");
        dinosaurs.Remove("Microraptor");

        Console.WriteLine("\nRemoveAt(0)");
        dinosaurs.RemoveAt(0);

        Display(dinosaurs);
    }
    
    private static void Display(Collection<string> cs)
    {
        Console.WriteLine();
        foreach( string item in cs )
        {
            Console.WriteLine(item);
        }
    }

    private static void ChangedHandler(object source, 
    DinosaursChangedEventArgs e)
    {

        if (e.ChangeType==ChangeType.Replaced)
        {
            Console.WriteLine("{0} was replaced with {1}", e.ChangedItem, 
            e.ReplacedWith);
        }
        else if(e.ChangeType==ChangeType.Cleared)
        {
            Console.WriteLine("The dinosaur list was cleared.");
        }
        else
        {
            Console.WriteLine("{0} was {1}.", e.ChangedItem, e.ChangeType);
        }
    }
}

上一篇:c# 如何使用结构体实现共用体

栏    目:.NET代码

下一篇:ASP.NET中HttpContext对象下的属性介绍

本文标题:C#集合之自定义集合类

本文地址:http://www.codeinn.net/misctech/212271.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有