[to] those years I still do not understand: ilist,icollection,ienumerable,ienumerator,iqueryable

Source: Internet
Author: User

1. First look at a simple example

Int[] MyArray = {1, +, 343};            IEnumerator Myie = Myarray.getenumerator ();            Myie. Reset ();            while (Myie. MoveNext ())            {                int i = (int) Myie. Current;                Console.WriteLine ("Value: {0}", i);            }
I'm sure a lot of people don't go through the myarray array like above, usually we do that.
            foreach (int item in MyArray)                Console.WriteLine (item. ToString ());
In most cases, many people use the for and foreach to iterate over the array, but the syntax for the above is rarely used, but the exact origin of the foreach is blurred!
2. Understanding foreach

We all know to implement the foreach must implement IEnumerable and IEnumerator interface, only implement them, can realize traversal, so to talk about the origin of foreach, must be the two interfaces to clear point!

Here also want to explain a point is: if the two interfaces have a certain understanding, as long as the implementation of the GetEnumerator method can, and do not need to implement the IEnumerable interface, this is only for the two interfaces have a certain understanding of the friends!

2.1 IEnumerable

The purpose of this is to make an object that implements this interface an enumerable type.

The IEnumerable interface contains a GetEnumerator method that returns a value of IEnumerator type! The code is as follows:

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

Then we can do this when the client makes the call!

            MyColors colors = new MyColors ();            foreach (string item in Colors)                Console.WriteLine (item);
This can be used to implement the object of this interface foreach traversal, is such a simple case, there may be some people will have doubts, we implemented the IEnumerable interface but did not implement the IEnumerator interface, But don't we say that only the two interfaces are implemented for a foreach traversal? It can be said that when using Forach to traverse, the compiler will go to the object's class to find the GetEnumerator method, find this method and return the object of this IEnumerator (enumerator), and my return is "colors." GetEnumerator () ", is an array object calls itself in the" GetEnumerator "method, so that the array itself implements the IEnumerator interface, then two interfaces are implemented, not a good implementation of the foreach traversal, In fact, when implementing a traversal enumerator, the compiler automatically calls the method in the class that implements the enumerator in the array.
2.2  IEnumerator

The function of the interface: to implement an enumerable, first look at the definition of the interface:

Contains a property of two methods

movenext→ moves the current item to the next item (similar to an index value) and returns a bool value that checks whether the current item is outside the enumerator range!

current→ gets the value of the current item and returns the type of the object (this will involve packing and unpacking problems → When the generics are referred to later)!

reset→, as the name implies, restores some values to their default values, such as returning the current item to the default state value!

    public class Myienumerator:ienumerator {public myienumerator (string[] colors) {this.co Lors = new string[colors.            Length];        for (int i = 0; i < this.colors.Length; i++) this.colors[i] = colors[i];        } string[] colors;      Defines an array that is used to store data int position =-1;        Define the default value of the current item, that is, the index value, the first to know the index of the array starting with "0",//How to set him to "1", the last to understand that this setting is reasonable!          public object Current//get the corresponding value {get {return colors[position] According to the present item;              Returns the value of the current item, but does a boxed operation! }} public bool MoveNext ()//move to the next item {if (Position < colors.                LENGTH-1)//This is the setting of the default value of-1 according to {position++;          return true;          } else {return false;        }}//Resets the value of the current item, reverts to the default value of public void Reset () {this.position =-1; }    }
The GetEnumerator method in the IEnumerable interface described above is to get the enumerator to traverse, and when we do not create our own class to iterate through the enumerator, we are using the array traversal method (the enumerable type of the array and the enumerator are discussed in the next article). But this is sometimes not suitable for us, we need to customize a more suitable for ourselves, so we want to create our own enumerator class (that is, the above code), the 3rd and 4th code together (change a little bit of code), as follows:
        public class MyColors   //: IEnumerable        {            string[] colors = {"Red", "Yellow", "Biue"};            Public IEnumerator GetEnumerator ()            {                return new myienumerator (colors);            }        
3. About enumerable types and enumerators

① enumerable type → implement IEnumerable interface, you can not directly implement this interface, but there must be a GetEnumerator method, the return value type must be the IEnumerator type, that is, the 4th of the last piece of code in the interface annotation that way!

② enumerator → Implement IEnumerator interface, implement all methods, first, call GetEnumerator returns an enumerator of type IEnumerator, then the compiler implicitly calls the implementation of the methods and properties in the IEnumerator Class!

Summary: So the implementation of the foreach traversal, must reach the above two conditions to traverse the object, they can be written together can also be separated, preferably separate, separation of duties, a class do one thing is always good! It also satisfies the design principle of object-oriented single accusation.

The following code example demonstrates how to implement the IEnumerable and IEnumerator interfaces of a custom collection (code 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, Strin            G 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 is 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[] Peo            Plearray = new Person[3] {    New Person ("John", "Smith"), the new person ("Jim", "Johnson"), the new person ("Sue", "Rabon"),            };            People peoplelist = new people (Peoplearray);        foreach (person p in Peoplelist) Console.WriteLine (P.firstname + "" + p.lastname); }    }}

No picture, no truth.

The following describes ilist,icollection,iqueryable

1. IList is the descendant of the ICollection interface and is the base interface for all non-generic lists. There are three categories of IList implementations: read-only, fixed-size, and variable-size. Read-only IList cannot be modified. Fixed-size IList does not allow the addition or removal of elements, but allows the modification of existing elements. The variable-size IList allows you to add, remove, and modify elements.

2. The ICollection interface is the base interface for classes in the System.Collections namespace. The ICollection interface extension ienumerable;idictionary and IList are more specialized interfaces for extended ICollection. The IDictionary implementation is a collection of key/value pairs, such as the Hashtable class.  An IList implementation is a collection of values whose members can be accessed through an index, such as the ArrayList class.  Some collections, such as the Queue class and the Stack class, restrict access to their elements, and they implement the ICollection interface directly. If both the IDictionary interface and the IList interface do not meet the requirements of the required collection, the new collection class is derived from the ICollection interface for increased flexibility. Defines the size, enumerator, and synchronization methods for all non-generic collections.

3. IQueryable provides the ability to compute queries for a specific data source that does not specify a data type, and the IQueryable interface is implemented by the query provider. The interface can only be implemented by a provider that implements IQueryable (of T) at the same time. If the provider does not implement IQueryable (of T), you cannot use the standard query operator with the provider data source. The IQueryable interface inherits the IEnumerable interface so that the results of the query can be enumerated when the former represents a query. Enumeration enforces the expression tree associated with the IQueryable object. The definition of execution expression tree is specific to the query provider. For example, it might involve converting an expression tree to a query language that is appropriate for the underlying data source. Queries that do not return enumerable results are executed when the Execute method is called.

[to] those years I still do not understand: ilist,icollection,ienumerable,ienumerator,iqueryable

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.