C#集合之自定义集合类

一、非泛型方式,继承自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#集合之自定义集合类的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#中IEnumerable接口介绍并实现自定义集合

    简介 IEnumerable接口是非常的简单,只包含一个抽象的方法GetEnumerator(),它返回一个可用于循环访问集合的IEnumerator对象.对于所有数组的遍历,都来自IEnumerable接口.IEnumerator对象有什么呢?它是一个真正的集合访问器,没有它,就不能使用foreach语句遍历集合或数组,因为只有IEnumerator对象才能访问集合中的项,假如连集合中的项都访问不了,那么进行集合的循环遍历是不可能的事情了. 一.foreach在IEnumerable中案例 p

  • C#使用yield关键字让自定义集合实现foreach遍历的方法

    foreach遍历是C#常见的功能,而本文通过实例形式展现了C#使用yield关键字让自定义集合实现foreach遍历的方法.具体步骤如下: 一般来说当我们创建自定义集合的时候为了让其能支持foreach遍历,就只能让其实现IEnumerable接口(可能还要实现IEnumerator接口) 但是我们也可以通过使用yield关键字构建的迭代器方法来实现foreach的遍历,且自定义的集合不用实现IEnumerable接口 注意:虽然不用实现IEnumerable接口 ,但是迭代器的方法必须命名为

  • C#如何自定义线性节点链表集合

    本例子实现了如何自定义线性节点集合,具体代码如下: using System; using System.Collections; using System.Collections.Generic; namespace LineNodeDemo { class Program { static void Main(string[] args) { LineNodeCollection lineNodes = new LineNodeCollection(); lineNodes.Add(new

  • C# 泛型集合的自定义类型排序的实现

    一.泛型集合List<T>排序 经sort方法之后,采用了升序的方式进行排列的. List<int> list = new List<int>() { 2, 4, 1, 3, 5, -2, 0, 10 }; Console.Write("排序前..."); foreach (var item in list) { Console.Write(item + "\t"); } list.Sort(); Console.WriteLin

  • C#入门学习之集合、比较和转换

    目录 一.集合 1.使用集合 2.自定义集合 3.索引符 4.关键字值集合和IDictionary 5.迭代器 6.迭代器和集合 7.深度复制 二.比较 1.类型比较 封箱和拆箱 is运算符 2.值比较 运算符重载 IComparable和IComparer接口 三.转换 1.重载转换运算符 2.as运算符 一.集合 C#中的数组是作为System.Array类的实例来执行的,它们是集合类中的一种. 集合类一般用于处理对象列表,其功能是通过执行System.Collection中的接口实现的.

  • C#集合之自定义集合类

    一.非泛型方式,继承自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

  • 集合Bootstrap自定义confirm提示效果

    本文实例为大家分享了集合Bootstrap自定义confirm的具体代码,供大家参考,具体内容如下 效果 这里写图片描述 js端 var Common = { confirm:function(params){ var model = $("#common_confirm_model"); model.find(".title").html(params.title) model.find(".message").html(params.mess

  • Java复习之集合框架总结

    俗话说:温故而知新.想想学过的知识,就算是以前学得很不错,久不用了,就会忘记,所以温习一下以前学习的知识我认为是非常有必要的.而本篇文件温习的是 Java基础中的集合框架. 为什么会有集合框架? 平时我们用数组存储一些基本的数据类型,或者是引用数据类型,但是数组的长度是固定的,当添加的元素超过了数组的长度时,需要对数组进行重新的定义,这样就会显得写程序太麻烦,所以Java内部为了我们方便,就提供了集合类,能存储任意对象,长度是可以改变的,随着元素的增加而增加,随着元素的减少而减少. 数组可以存储

  • Java集合类之TreeSet的用法详解

    目录 上节回顾 TreeSet集合概述和特点 构造方法 方法摘要 Demo 自然排序Comparable的使用 比较器排序Comparator的使用 上节回顾 LinkedHashSet集合概述及特点 LinkedHashSet集合特点 哈希表和链表实现Set接口,具有可预测的迭代次序 由链表保证元素有序,也就是说元素的存储和取出顺序是一致的 由哈希表保证元素唯一,也就是说没有重复元素 LinkedHashSet集合的储存和遍历: import java.util.LinkedHashSet;

  • Java中ArrayList去除重复元素(包括字符串和自定义对象)

    1.去除重复字符串 package com.online.msym; import java.util.ArrayList; import java.util.Iterator; @SuppressWarnings({ "rawtypes", "unchecked" }) public class Demo1_ArrayList { public static void main(String[] args) { ArrayList list = new Array

  • Java 基础详解(泛型、集合、IO、反射)

    计划把 Java 基础的有些部分再次看一遍,巩固一下,下面以及以后就会分享自己再次学习的一点笔记!不是有关标题的所有知识点,只是自己觉得模糊的一些知识点. 1.对于泛型类而言,你若没有指明其类型,默认为Object: 2.在继承泛型类以及接口的时候可以指明泛型的类型,也可以不指明: 3.泛型也数据库中的应用: 写一个 DAO 类对数据库中的数据进行增删改查其类型声明为 <T> .每张表对应一个类,对应每一张表实现一个类继承该 DAO 类并指明 DAO 泛型为该数据表对应的类,再实现一个与该表匹

  • .Net中的集合排序可以这么玩你知道吗

    C#集合类型概述 集合是.NET FCL(Framework Class Library)中很重要的一部分.所有的集合类都继承自IEnumerable.集合类总体可分为一下几类:关联/非关联型集合,顺序/随机访问集合,顺序/无序集合,泛型/非泛型集合,线程安全集合. 各集合类底层接口关系图 背景: public class StockQuantity { public StockQuantity(string status, DateTime dateTime, int quantity) {

  • Java基础之集合框架详解

    一.前言 本节学习到的内容有以下5类,不分先后顺序: 集合Collection体系结构 List子类 与集合结合使用的迭代器对象 集合与数组的区别? 常见的一般数据结构整理 二.集合的由来? Collection List ArrayList Vector LinkedList Set hashSet treeSet 在集合没有出现之前,使用对象数组来存储对象,但是,对象数组的长度一旦确定,则不可以发生变化,所以我们希望存在一个容器就像StringBuffer一样存储字符串,同时依据传入的值的个

  • JAVA容器集合全面解析(Collection和Map)

    目录 前言 一.Collection集合 1.1List集合 1.1.1ArrayList集合 1.1.2LinkedList集合 1.2Set集合 1.2.1HashSet集合 HashSet集合保证元素唯一性源码分析: 1.2.2TreeSet集合 比较器排序Comparator的使用: 二.Map集合 2.1Map集合的概述与特点 2.2Map集合的获取功能 2.3Map集合的遍历方式(方式一) 2.4Map集合的遍历方式(方式二) 2.5HashMap集合 前言 本次我将分享的是java

随机推荐