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

相关推荐
Pluto_CSND30 分钟前
Java中的静态代理与动态代理(Proxy.newProxyInstance)
java·开发语言
惊讶的猫2 小时前
LSTM论文解读
开发语言·python
獨枭3 小时前
C# 本地项目引用失效与恢复全攻略
开发语言·c#·visual studio
清风与日月3 小时前
c# 上位机作为控制端与下位机通信方式
单片机·嵌入式硬件·c#
国服第二切图仔4 小时前
Rust开发之Trait 定义通用行为——实现形状面积计算系统
开发语言·网络·rust
mjhcsp4 小时前
C++ 循环结构:控制程序重复执行的核心机制
开发语言·c++·算法
A阳俊yi4 小时前
Spring Data JPA
java·开发语言
csbysj20204 小时前
CSS 对齐
开发语言
爱吃巧克力的程序媛4 小时前
将qt界面中加载css或者qss样式
开发语言·css·qt