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# 语法总目录

相关推荐
互联网中的一颗神经元6 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
Wang's Blog6 小时前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
a1117767 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
Wang's Blog9 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
code bean9 小时前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
吃好睡好便好11 小时前
MATLAB中图像的读取、写入和显示
开发语言·图像处理·学习·计算机视觉·matlab
yaoxin52112312 小时前
476. Java 反射 - 调用方法
java·开发语言
猫头虎12 小时前
什么是ZCode for GLM-5.2?
开发语言·人工智能·python·科技·算法·ai编程·ai写作
吴可可12313 小时前
C# CAD二次开发:合并首尾重合多段线
c#
bksczm13 小时前
Linux之日志和线程池、内存池
java·开发语言