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

相关推荐
我不是程序猿儿3 分钟前
【C】识别一份嵌入式工程文件
c语言·开发语言
软件开发技术局1 小时前
撕碎QT面具(8):对控件采用自动增加函数(转到槽)的方式,发现函数不能被调用的解决方案
开发语言·qt
周杰伦fans2 小时前
C#中修饰符
开发语言·c#
yngsqq3 小时前
c# —— StringBuilder 类
java·开发语言
赔罪3 小时前
Python 高级特性-切片
开发语言·python
avi91114 小时前
[AI相关]Unity的C#代码如何简写
unity·c#·语法糖
子豪-中国机器人4 小时前
2月17日c语言框架
c语言·开发语言
夏天的阳光吖4 小时前
C++蓝桥杯基础篇(四)
开发语言·c++·蓝桥杯
oioihoii4 小时前
C++17 中的 std::to_chars 和 std::from_chars:高效且安全的字符串转换工具
开发语言·c++
秋窗75 小时前
Mac下Python版本管理,适用于pyenv不起作用的情况
开发语言·python·macos