C#学习笔记之集合(入门经典 11.)

来源:互联网 发布:word2003软件 编辑:程序博客网 时间:2024/05/22 03:37

    集合类的大多功能是通过实现System.Collection命名空间之中的接口而获得的。


    1.IEnumerable可以迭代集合中的项。
    2.ICollection(继承于IEnumerable)可以获取集合中项的个数,并能把项复制到一个简单的数组类型中。
    3.IList(继承自IEnumerable和ICollection)提供了集合的项列表,允许访问这些项及一些相关的基本功能。
    4.IDictionary还提供了键值。
    
    一、System.Collection.ArrayList类: 动态数组,实现了ICollection,IList,IEnumerable,ICloneable接口。
一般常用的属性方法有:  Count, Capacity, 
Add(object value), Remove(object value), 
CopyTo(Array array),Clone(), 
IndexOf(object value)等。

    二、Indexer(索引器): 使得类中的对象能像数组那样方便、直观的被引用。
    定义格式:
<accessType> <returnType> this[<argument list>]

    get{}
    set{}
}
    索引器与数组、属性的区别:
(1)索引器的索引值类型不受限于整型;
(2)索引器可以重载,但其函数签名由其参数类型及数量来决定;
(3)索引器没有直接存储的地方,不同于数组,其更像是桥梁,通过索引器可以访问其归属对象内的其他成员。
(4)索引器使用当前对象this,不能是静态的。


    抽象基类: CollectionBase、DictionaryBase.
    DictionaryBase的实例对象的foreach遍历可以使用 DictionaryRetry.

    三、迭代器
迭代器是方法、get访问器或运算符,支持foreach迭代,而不必实现整个IEnumerable接口。
迭代器代码使用 yield return 依次返回每个元素,yield break将终止迭代。
迭代器的返回类型必须为IEnumerable、IEnumerator、IEnumerable<T>和IEnumerator<T>.
yield关键字用于指定返回的值。到达yield return语句时,会保存当前位置,下次调用迭代器时将从此位置重新开始执行。


当编译器检测到迭代器时,自动生成IEnumerable或IEnumerable<T>接口的Current、MoveNext和Dispose方法。
若迭代一个类,使用方法GetEnumerator(), 返回类型IEnumerator.
若迭代类成员,使用IEnumerable。
       ICloneable接口的成员 Clone 可实现深复制


     迭代器示例.

     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 possiblePrimer = min; possiblePrimer < max; possiblePrimer++)
            {
                bool isPrimer = true;
                for(long possible = 2; possible < (long)Math.Floor(Math.Sqrt(possiblePrimer)); possible++)
                {
                    long num = possiblePrimer % possible;
                    if(num == 0)
                    {
                        isPrimer = false;
                        break;
                    }
                }
                if(isPrimer)
                {
                    yield return possiblePrimer;
                }
            }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Primes myPrimes = new Primes(2, 1000);

            foreach(long num in myPrimes)
            {
                Console.Write(num + "  ");
            }
        }
    }




0 0
原创粉丝点击