C#集合、定义集合、索引符、List<T>、Dictionary<K,V>、键控集合(键值)和IDictionary

目录

一、集合

二、使用集合

三、定义集合

四、索引符

五、使用List泛型集合类

六、键控集合和IDictionary

七、使用Dictionary<K,V>泛型集合类


一、集合

集合类Collection Class

C#中的数组实现为System.Array类的实例,只是集合类中的一种类型

集合类一般用于处理对象列表,功能大多是通过实现System.Collections名称空间中的接口而获得

集合的功能(包括基本功能)可以通过接口来实现,可以使用基本集合类(System.Array),可以创建定制集合类

System.Collections名称空间中的几个接口提供了基本的集合功能:

IEnumerable可以迭代集合中的项

ICollection(继承于IEnumerable)可以获取集合中项的个数,并能把项复制到一个简单的数组类型中

IList(继承于IEnumerable和ICollection)提供了集合的项列表,允许访问这些项,并提供其他一些与项列表相关的基本功能

IDictionary(继承于IEnumerable和ICollection)类似于IList,但提供了可通过键值(而不是索引)访问的项列表

System.Array类实现了IList、ICollection和IEnumerable,但不支持IList的一些更高级功能,它表示大小固定的项列表

二、使用集合

Systems.Collections名称空间中的类System.Collections.ArrayList也实现了IList、ICollection和IEnumerable接口,但实现方式比System.Array更复杂。

System.Array数组的大小是固定不变的(不能添加或删除元素)

System.Collections.ArrayList类可以用于表示大小可变的项列表

代码参考:

https://media.wiley.com/product_ancillary/85/11190966/DOWNLOAD/Chapter11code.zip

准备好的基类和派生类先写在这里,使用的命名空间都是Animals

基类 Animal.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace Animals
{   
    /// <summary>
    /// 
    /// </summary>
    public abstract class Animal
    {
        protected string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public Animal()
        {
            name = "The animal with no name";
        }

        public Animal(string newName)
        {
            name = newName;
        }

        public void Feed() => WriteLine($"{name} has been fed.");
    }
}

派生类 Cow.cs  Chicken.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace Animals
{
    public class Cow : Animal
    {
        public void Milk() => WriteLine($"{name} has been milked.");

        public Cow(string newName) : base(newName) { }
    }
}
usin
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值