IList, ICollection, IEnumerable, IEnumerator, IQueryable, ilisticollection

Source: Internet
Author: User

IList, ICollection, IEnumerable, IEnumerator, IQueryable, ilisticollection

Http://www.cnblogs.com/edison1105/archive/2012/07/30/2616082.html

 

1. First, let's look at a simple example.

int[] myArray = { 1, 32, 43, 343 };            IEnumerator myie = myArray.GetEnumerator();            myie.Reset();            while (myie.MoveNext())            {                int i = (int)myie.Current;                Console.WriteLine("Value: {0}", i);            }
I believe that many people will not traverse the array of myArray as above. We usually do this.
            foreach (int item in myArray)                Console.WriteLine(item.ToString());
 
In most cases, many people use for and foreach to traverse arrays, but the above syntax is rarely used, but the specific origins of foreach are still vague!
 
 
2. Understanding foreach

We all know that to implement foreach, you must implement the interfaces of IEnumerable and IEnumerator. Only when you implement them can you traverse them, you must clarify the two interfaces!

One thing to note here is: if you have some knowledge about these two interfaces, you only need to implement the GetEnumerator method, instead of the IEnumerable interface, this is just for friends who have some knowledge about these two interfaces!

 

2.1 IEnumerable

 

The specific function is to make the object implementing this interface an enumerated type.

 

The IEnumerable Interface contains a GetEnumerator method. The returned value is of the IEnumerator type! The Code is as follows:

    public class MyColors : IEnumerable    {        string[] colors = { "Red", "Yellow", "Biue" };        public IEnumerator GetEnumerator()        {            return colors.GetEnumerator();        }    }

So we can do this when calling the client!

            MyColors colors = new MyColors();            foreach (string item in colors)                Console.WriteLine(item);
In this way, the object implementing this interface can be used for foreach traversal. This is a simple column, and some people may have questions, we implemented the IEnumerable interface but did not implement the IEnumerator interface. But we didn't mean that only the two interfaces can be used for foreach traversal? It can be said that when we use forach for traversal, the compiler will go to the class of this object to find the GetEnumerator method, find this method, and return this IEnumerator object (enumeration number ), here I return "colors. getEnumerator () "is an array object that calls its" GetEnumerator "method. Therefore, the array itself implements the IEnumerator interface, and both interfaces are implemented, in fact, the compiler will automatically call the method in the array to implement the enumerated number class when traversing the enumerated number.
2.2  IEnumerator

Function of the interface: implement the number of enumerable items. First, let's take a look at the interface definition:

 

 

Contains one attribute and two methods.

MoveNext → Move the current item to the next item (similar to the index value) and return a bool value. This bool value is used to check whether the current item has exceeded the enumerated value range!

 

Current → get the value of the Current item and return the type of an object (this will involve the problem of packing and unpacking → it will be involved later when talking about generics )!

 

Reset → as the name suggests, it restores some values to the default value, for example, restoring the current item to the default value!

Public class MyIEnumerator: IEnumerator {public MyIEnumerator (string [] colors) {this. colors = new string [colors. length]; for (int I = 0; I <this. colors. length; I ++) this. colors [I] = colors [I];} string [] colors; // defines an array to store int position =-1; // defines the default value of the current item, that is, the index value. At first, we realized that the index of the array starts from "0". // how can we set it to "-1" by default, this setting is reasonable! Public object Current // obtain the corresponding value {get {return colors [position] based on the Current item; // return the value of the Current item, but a boxing operation will be performed! } Public bool MoveNext () // move to the next {if (position <colors. length-1) // set the default value to-1 based on {position ++; return true;} else {return false ;}// reset the value of the current item, restore to the default value public void Reset () {this. position =-1 ;}}
In the IEnumerable interface mentioned above, the GetEnumerator method is used to obtain the number of enumerations to be traversed, we use the method of traversing the enumerated Number of Array (the enumerated types and enumerated numbers of arrays will be discussed in the next article), but sometimes this is not necessarily suitable for us, we need to customize a more appropriate one for ourselves, so we need to create our own enumerated number class (that is, the code above ), combine the code of the third and fourth points (change the code) as follows:
        public class MyColors   //: IEnumerable        {            string[] colors = { "Red", "Yellow", "Biue" };            public IEnumerator GetEnumerator()            {                return new MyIEnumerator(colors);            }        }
 
3. About the enumerated types and enumerated numbers
 

① Enumeration type → implement the IEnumerable interface. You do not need to implement this interface directly, but you must have a GetEnumerator method. The return value type must be IEnumerator, that is, the method for writing interface comments in the last code section at the fourth point!

② Enumeration count → implement the IEnumerator interface to implement all the methods. First, call GetEnumerator to return an enumeration number of IEnumerator type, and then the compiler will implicitly call the methods and attributes in the IEnumerator class!

 

Conclusion: To achieve foreach traversal, the objects can be traversed only when the preceding two conditions are met. They can be written together or separated. It is best to separate roles and responsibilities, it is always a good thing to do one thing! It also meets the single object-oriented accusation design principles.

 

The following code example demonstrates how to implement the IEnumerable and IEnumerator interfaces of a custom set (the code is from MSDN)

using System;using System.Collections;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{    public class Person    {        public Person(string fName, string lName)        {            this.firstName = fName;            this.lastName = lName;        }        public string firstName;        public string lastName;    }    public class People : IEnumerable    {        private Person[] _people;        public People(Person[] pArray)        {            _people = new Person[pArray.Length];            for (int i = 0; i < pArray.Length; i++)            {                _people[i] = pArray[i];            }        }        IEnumerator IEnumerable.GetEnumerator()        {            return (IEnumerator)GetEnumerator();        }        public PeopleEnum GetEnumerator()        {            return new PeopleEnum(_people);        }    }    public class PeopleEnum : IEnumerator    {        public Person[] _people;        // Enumerators are positioned before the first element        // until the first MoveNext() call.        int position = -1;        public PeopleEnum(Person[] list)        {            _people = list;        }        public bool MoveNext()        {            position++;            return (position < _people.Length);        }        public void Reset()        {            position = -1;        }        object IEnumerator.Current        {            get            {                return Current;            }        }        public Person Current        {            get            {                try                {                    return _people[position];                }                catch (IndexOutOfRangeException)                {                    throw new InvalidOperationException();                }            }        }    }    class Program    {        static void Main(string[] args)        {            Person[] peopleArray = new Person[3]            {                new Person("John", "Smith"),                new Person("Jim", "Johnson"),                new Person("Sue", "Rabon"),            };            People peopleList = new People(peopleArray);            foreach (Person p in peopleList)                Console.WriteLine(p.firstName + " " + p.lastName);        }    }}

 

No picture, no truth

 

I am not a title party. Here we will introduce IList, ICollection, and IQueryable.

 

1. IList is the child of the ICollection interface and is the base interface of all non-generic lists. There are three types of IList implementation: Read-only, fixed size, and variable size. The read-only IList cannot be modified. A fixed-size IList cannot add or remove elements, but can modify existing elements. Variable-size IList allows you to add, remove, and modify elements.

 

2. The ICollection interface is the base interface of the class in the System. Collections namespace. ICollection interface extends IEnumerable; IDictionary and IList are more dedicated interfaces for extending ICollection. IDictionary is a set of key/value pairs, such as the Hashtable class. The IList implementation is a set of values, and its members can be accessed through indexes, such as the ArrayList class. Some collections (such as the Queue and Stack classes) restrict access to their elements. They directly implement the ICollection interface. If neither the IDictionary interface nor the IList interface meets the requirements of the required collection, a new collection class is derived from the ICollection interface to improve flexibility. Defines the size, enumerator, and Synchronization Methods of all non-generic sets.

 

3. IQueryable provides the function of calculating queries for specific data sources without specified data types. The IQueryable interface is implemented by the query provider. This interface can only be implemented by the provider that implements IQueryable (Of T) at the same time. If the provider does not implement IQueryable (Of T), standard query operators cannot be used for the provider data source. The IQueryable interface inherits the IEnumerable interface, so that when the former represents a query, You can enumerate the query results. The enumeration enforces the Expression Tree associated with the IQueryable object. The execution Expression Tree is unique to the query provider. For example, it may involve converting the expression tree to a query language suitable for the basic data source. When the Execute method is called, a query that does not return enumerated results will be executed.

 

Sorry, I will give you a rough introduction here. I am too lazy and will go to work tomorrow. I will continue to work next time...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.