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 Flask文件处理与异常处理实战指南
开发语言·python·自然语言处理·flask·python3.11
贩卖纯净水.15 分钟前
浏览器兼容-polyfill-本地服务-优化
开发语言·前端·javascript
k要开心21 分钟前
C++概念以及基础框架语法
开发语言·c++
开发者工具分享1 小时前
如何应对敏捷转型中的团队阻力
开发语言
gregmankiw1 小时前
C#调用Rust动态链接库DLL的案例
开发语言·rust·c#
roman_日积跬步-终至千里2 小时前
【Go语言基础【20】】Go的包与工程
开发语言·后端·golang
秦少游在淮海2 小时前
C++ - string 的使用 #auto #范围for #访问及遍历操作 #容量操作 #修改操作 #其他操作 #非成员函数
开发语言·c++·stl·string·范围for·auto·string 的使用
const5442 小时前
cpp自学 day2(—>运算符)
开发语言·c++
心扬2 小时前
python生成器
开发语言·python
阿蒙Amon2 小时前
06. C#入门系列【自定义类型】:从青铜到王者的进阶之路
开发语言·c#