C#之Collection<T>类的学习

C#之Collection类的学习

学习.Net常用基类之Collection<>类的常用属性和方法的学习和继承Collection<>类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
/// <summary>
/// This section contains two code examples.The first example demonstrate several properties and
/// methods of Collection<T>.The second example shows how to derive a collection class from a 
/// constrcuted typed of Collection<T>,and how to override the protected methods of Collection<T>
/// to provide custom behavior.
/// </summary>
namespace 练习基类
{
    class Program
    {
        static void Main(string[] args)
        {
            #region Example 1
            // The following code exmaple demonstrate many of the properties and methods of Collection<T>.The code 
            // example creates a collection of string,uses the Add method to add several strings,displays the count,and 
            // lists the string.

            //Collection<string> subjets = new Collection<string>();
            //subjets.Add("English");
            //subjets.Add("Math");
            //subjets.Add("PE");
            //subjets.Add("COmputer");
            //subjets.Add("Calculas");

            //Console.WriteLine($"the number of subjects is:{subjets.Count}");
            //Display(subjets);
            #endregion


            #region Example 2
            // The following code demonstrate how to derive a collection class from a constrcuted typed of
            // the Collection<T> class.And how to override the protected method InsertItem,RemoveItem,
            // ClearItems and SetItem methods to provide custom behavior  for the Add,Insert,and Clear 
            // methods,and for the setting item property.

            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);
            #endregion

            Console.ReadKey();
        }

        private static void ChangedHandler(object sender, DinosaursChangedEventArgs e)
        {
           if(e.changedType==ChangedType.Replaced)
            {
                Console.WriteLine($"{e.ChangedItem} was replaced with {e.ReplaceWith}");
            }
           else if(e.changedType==ChangedType.Cleared)
            {
                Console.WriteLine("the dinosaurs list was cleared");
            }
           else
            {
                //Console.WriteLine("{0} was {1}.", e.ChangedItem, e.ChangeType);
            }
        }
        /// <summary>
        /// Display members of a Collection
        /// </summary>
        /// <param name="strs"></param>
        public static void Display(Collection<string> strs)
        {
            foreach(string str in strs)
            {
                Console.WriteLine(str);
            }
        }
    }
    public class Dinosaurs:Collection<string>
    {
        public event EventHandler<DinosaursChangedEventArgs> Changed;

        protected override void InsertItem(int index, string item)
        {
            base.InsertItem(index, item);
            EventHandler<DinosaursChangedEventArgs> temp = Changed;
            if(temp!=null)
            {
                temp(this, new DinosaursChangedEventArgs(ChangedType.Added, item, null));
            }

        }
        protected override void SetItem(int index, string item)
        {
            string replaced = Items[index];
            base.SetItem(index, item);
            EventHandler<DinosaursChangedEventArgs> temp = Changed;
            if(temp!=null)
            {
                temp(this, new DinosaursChangedEventArgs(ChangedType.Replaced, replaced, item));
            }
        }
        protected override void ClearItems()
        {
            base.ClearItems();
            EventHandler<DinosaursChangedEventArgs> temp = Changed;
            if (temp != null)
            {
                temp(this, new DinosaursChangedEventArgs(ChangedType.Remove, null, null));
            }
        }
        protected override void RemoveItem(int index)
        {
            string removed = Items[index];
            base.RemoveItem(index);
            EventHandler<DinosaursChangedEventArgs> temp = Changed;
            if (temp != null)
            {
                temp(this, new DinosaursChangedEventArgs(ChangedType.Remove, removed, null ));
            }
        }
    }
    // Event argument for the changed event
    public class DinosaursChangedEventArgs:EventArgs
    {
        public readonly string ChangedItem;
        public readonly ChangedType changedType;
        public readonly string ReplaceWith;
        public DinosaursChangedEventArgs(ChangedType change,string item,string replacement  )
        {
            this.changedType = change;
            this.ChangedItem = item;
            this.ReplaceWith = replacement;
        }
    }
    public enum ChangedType
    {
        Added,
        Remove,
        Replaced,
        Cleared
    };
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值