C# 集合

1 使用集合

using System;
using System.Collections;

namespace Ch11Ex01
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "";

            str = $"{1}+{2}={3}";
            Console.WriteLine(str);

            str = string.Format("{0}+{1}={2}", 1, 2, 3);
            Console.WriteLine(str);
            
			//因为数组是引用类型,用一个长度初始化数组并没有初始化它所包含的项
			//要使用一个指定的项,则还需要对该项初始化
            Animal[] animals = new Animal[2];
            Cow cow = new Cow("花花");
            cow.Milk();
            cow.Feed();
            animals[0] = cow;//将Cow强制类型转换为Animal,当然其Milk方法也会随之消失,
            animals[0].Feed();

            animals[1] = new Chicken("波波");
            animals[1].Feed();//此时波波并没有下蛋方法

            Chicken chc = (Chicken)animals[1];
            //数组类型是抽象类型Animal,因此不能直接调用派生类的方法,必须进行强制类型转换
            ((Chicken)animals[1]).LayEgg();
            chc.LayEgg();//Animal转回Chicken,波波重新获得了下蛋方法

            Cow cow2 = new Cow("大牛");
            Cow cow3 = new Cow("二牛");

    		//对于ArrayList集合,它没有现成的项,也没有null引用的项。这样我们就需要使用Add()方法添加新项了。
            ArrayList animalList = new ArrayList();
            animalList.Add(cow);//添加项
            animalList.Add(cow2);
            animalList.Add(cow3);
            animalList.Add(chc);
            animalList.Add(cow);
            animalList.AddRange(animals);//一次添加多项
            animalList.RemoveAt(animalList.Count - 1);//删除项
            animalList.Remove(cow2);//删除项

            Console.WriteLine();
            //foreach结构迭代数组或ArrayList
            foreach (Animal a in animalList)
            {
                Console.Write(a.Name+",");
            }
            Console.WriteLine();
        }
    }
}
using System;

namespace Ch11Ex01
{
    public abstract class Animal
    {
        protected string name;//字段
        public string Name//属性
        {
            get { return this.name; }//访问器
            set { this.name = value; }//访问器
        }

        public Animal()
        {
            name = "无名";
        }
        public Animal(string name)
        {
            this.name = name;
        }

        public void Feed()
        {
            Console.WriteLine($"{name}已经被喂过了");
        }
    }
}
using System;

namespace Ch11Ex01
{
    class Cow:Animal
    {
        public void Milk() => Console.WriteLine($"{name}挤奶");
        public Cow(string newName) : base(newName) { }
    }
}

using System;

namespace Ch11Ex01
{
    class Chicken:Animal
    {
        public void LayEgg() => Console.WriteLine($"{name}下蛋");
        public Chicken(string newName):base(newName){ }
    }
}
  • 这个示例中有两个对象集合:System.Array类 和 System.Collections.ArrayList类
  • 这两个集合的对象都是Animal,而Animal类是抽象类,所以不能进行实例化。
  • 通过多态性,使集合中的项成为派生于Animal类的Cow和Chicken类,从而实现了实例化。
  • 集合的创建,对于简单数组而言,初始化时必须要固定数组长度。而ArrayList集合是不需要初始化其大小的。

2 创建集合

  • 如何创建强类型化的集合?
  • 在上面的例子的基础上增加一个Animals类
    class Animals:CollectionBase
    {
        public void Add(Animal newAnimal) => List.Add(newAnimal);
        public void Remove(Animal newAnimal) => List.Remove(newAnimal);

        //索引符是一种特殊的属性,可以把它添加到一个类中,已提供类似于数组的访问
        //this关键字需要与方括号中的参数一起使用,除此之外索引符与其他属性十分类似。
        public Animal this[int animalIndex]
        {
            get
            {
                return (Animal)List[animalIndex];
            }
            set
            {
                List[animalIndex] = value;
            }
        }
    }
namespace Ch11Ex02
{
    class Program
    {
        static void Main(string[] args)
        {
            Animals animalCollection = new Animals();
            animalCollection.Add(new Cow("花花"));
            animalCollection.Add(new Chicken("华华"));
            foreach (Animal item in animalCollection)
            {
                item.Feed();
            }
        }
    }
}
  • 以上实现了Animals类中强类型化的Animal对象集合。

3 键控集合和IDictionary

  • 除了实现IList接口外,集合还可以实现类似的IDictionary接口,允许项通过键值(如字符串名)进行索引,而不是通过一个索引。这也可以使用索引符来完成,但这次使用的索引符参数是一个与存储的项相关联的键,而不是int索引,这样集合就更便于用户使用了。
    class Animals2 : DictionaryBase
    {
        public void Add(string newID, Animal newAnimal) => Dictionary.Add(newID, newAnimal);
        public void Remove(Animal newAnimal) => Dictionary.Remove(newAnimal);
        public Animals2() { }
        public Animal this[string animalID]
        {
            get { return (Animal)Dictionary[animalID]; }
            set { Dictionary[animalID] = value; }
        }
    }
using System;
using System.Collections;

namespace Ch11Ex02
{
    class Program
    {
        static void Main(string[] args)
        {
            Animals animalCollection = new Animals();
            animalCollection.Add(new Cow("花花"));
            animalCollection.Add(new Chicken("华华"));
            foreach (Animal item in animalCollection)
            {
                item.Feed();
            }
            
            Animals2 animalDictionary = new Animals2();
            animalDictionary.Add("1",new Cow("花花"));
            animalDictionary.Add("3",new Chicken("华华"));
            foreach (DictionaryEntry myEntry in animalDictionary)
            {
                Console.WriteLine(myEntry.Value.ToString());
                ((Animal)myEntry.Value).Feed();
            }
        }
    }
}

4 迭代器

  • 枚举素数集合
using System;
using System.Collections;

namespace Ch11Ex03
{
    public class Primes
    {
        private long min;
        private long max;
        public Primes() : this(2, 100) { }
        public Primes(long minimum,long maximum)
        {
            if (minimum < 2)
                min = 2;
            else
                min = minimum;
            max = maximum;
        }
        public IEnumerator GetEnumerator()
        {
            for (long possiblePrime = min; possiblePrime <= max; possiblePrime++)
            {
                bool isPrime = true;
                for (long possibleFactor = 2; possibleFactor <= (long)Math.Floor(Math.Sqrt(possiblePrime)); possibleFactor++)
                {
                    long remainderAfterDivision = possiblePrime % possibleFactor;
                    if (remainderAfterDivision==0)
                    {
                        isPrime = false;
                        break;
                    }
                }
                if (isPrime)
                {
                    yield return possiblePrime; 
                }
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Primes primesFrom2To1000 = new Primes(2, 1000);
            foreach (long item in primesFrom2To1000)
            {
                Console.Write($"{ item} ");
            }
            Console.ReadKey();
        }
    }
}
  • 在1.3中Animals2类中添加迭代器,如下:
        //迭代器
        public new IEnumerator GetEnumerator()
        {
            foreach (object animal in Dictionary.Values)
            {
                yield return (Animal)animal;
            }
        }
  • 那么就可以像列表那样去访问其中的对象了。
            foreach (Animal a in animalDictionary)
            {
                a.Feed();
            }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MechMaster

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值