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

总目录
C# 语法总目录

集合六 Collection

1. 自定义集合Collection

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

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;
    }
}
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");
    }
}
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

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

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值