C# 集合(六) —— 自定义集合Collection类

总目录
C# 语法总目录

集合六 Collection

  • [1. 自定义集合Collection](#1. 自定义集合Collection)
  • 其他

1. 自定义集合Collection

Collection可以对添加删除元素或者添加删除属性进行事件响应。

csharp 复制代码
class Person
{
    public string name;
    public int age;
    public Person()
    {
        this.name = "";
        this.age = 0;
    }

    public Person(string name, int age)
    {
        this.name = name;
        this.age = age;
    }
    public override string ToString()
    {
        return this.name + "," + this.age;
    }
}
csharp 复制代码
class PersonCollection : Collection<Person>
{
    protected override void InsertItem(int index, Person item)
    {
        base.InsertItem(index, item);
        Console.WriteLine("insert ele: index id {0},item is {1}",index,item.ToString());
    }
    protected override void SetItem(int index, Person item)
    {
        base.SetItem(index, item);
        Console.WriteLine("set ele: index id {0},item is {1}", index, item.ToString());
    }
    protected override void RemoveItem(int index)
    {
        base.RemoveItem(index);
        Console.WriteLine("remove ele: index id {0}", index);
    }

    protected override void ClearItems()
    {
        base.ClearItems();
        Console.WriteLine("collect is clear");
    }
}
csharp 复制代码
internal class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, World!");
        PersonCollection people = new PersonCollection();
        people.Add(new Person());
        
        people.Insert(0, new Person("lisi", 50));
        people[1] = new Person("anger", 19);
        people.RemoveAt(1);

        foreach (var item in people)
        {
            Console.WriteLine(item.ToString());
        }

    }
}

其他

方法:string.Compare

csharp 复制代码
string str1 = "help";
string str2 = "Help";
string str3 = "help";

int res = string.Compare(str1, str2);
int res1 = string.Compare(str1, str3);
Console.WriteLine(res);     //-1
Console.WriteLine(res1);    //0

总目录
C# 语法总目录

相关推荐
毕设源码-邱学长7 小时前
【开题答辩全过程】以 基于Java企业人事工资管理系统为例,包含答辩的问题和答案
java·开发语言
周杰伦fans7 小时前
C# 正则表达式完全指南
mysql·正则表达式·c#
颜*鸣&空8 小时前
QT程序实现串口通信案例
开发语言·qt
无限进步_8 小时前
C语言动态内存的二维抽象:用malloc实现灵活的多维数组
c语言·开发语言·数据结构·git·算法·github·visual studio
froginwe118 小时前
Maven 仓库概述
开发语言
二川bro9 小时前
Python在AI领域应用全景:2025趋势与案例
开发语言·人工智能·python
Triumph++9 小时前
电器模C#汇控电子继块驱动(Modbus协议)
c#·visual studio·c#串口通信
CoderYanger9 小时前
优选算法-队列+宽搜(BFS):72.二叉树的最大宽度
java·开发语言·算法·leetcode·职场和发展·宽度优先·1024程序员节
疏狂难除10 小时前
随便玩玩lldb (二)
开发语言·后端·rust