C # Learning Diary----Two-dimensional indexer and foreach traversal indexer

Source: Internet
Author: User
At the end of the last time I left a few questions, because the power is not resolved, this one we continue the content of the previous article. Click here to go back to the previous article

Question 1:

Arrays have multidimensional, indexers can also be multidimensional???

Indexers can be multidimensional, and the indexer we define in the previous article is just a one-dimensional indexer, and as an array you can define a multidimensional indexer. For example, we index the cinema of a screening room seat number, the first row of the first column 1th, a row of 2 column 2nd ... As follows:

Using System;  Using System.Collections.Generic;  Using System.Linq;    Using System.Text; namespace Test1 {///Definition Cinema class contains a two-dimensional array with a two-dimensional accessor class Cinema {//defines a two-dimensional array private string[,] seat = new Str      Ing[5, 5];              Define a two-dimensional accessor public string this[uint A, uint b] {get {return seat[a, b];}                    set {seat[a, b] = value;}  }} class Program {static void Main (string[] args) {Cinema movieroom                  = new Cinema ();//instantiate//for loop traversal write for (UINT i = 1; i < 5; i++) {                  for (UINT j = 1; j < 5; J + +) {movieroom[i, j] = "First" + i + "row" + j + "column";                  }}//for loop traversal read for (UINT i = 1; i < 5; i++) { for (UINT j = 1; j < 5; J + +) {Console.WriteLine (Movieroom[i,j]+ "\ T" + ((i-1) *4+j) + "number"); }                            }          }      }  }

Results:

The two-dimensional indexer is so, the other multidimensional number of the same and so on, do not introduce.

Question 2:

Arrays can be easily and quickly traversed using a foreach statement, and can the indexer traverse with a foreach statement???

This is also possible, in solving this problem, it is necessary to clarify the implementation of the process of foreach and the principle.

foreach statement:

In C #, the compiler translates the foreach statement into the methods and properties of the IEnumerable interface, such as:

string[] str = new string[] {"HC1", "HC2", "HC3", "HC4"};//define an array of              foreach (string i in str)//Use foreach traversal              {                  C Onsole. WriteLine (i);              }

However, the foreach statement is parsed into the following code snippet.

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;  Using System.Collections; Note Add this namespace, otherwise there is no IEnumerator this class    namespace Example  {class program      {          static void Main (string[] args)          {              string[] str = new string[] {"HC1", "HC2", "HC3", "HC4"};//define an array            //Call the GetEnumerator () method, Gets an enumeration of the array              IEnumerator per = str. GetEnumerator ();            In the while loop, as long as MoveNext () returns True, it is looped down while              (per). MoveNext ())              {                  //Use the current property to access the element in the array,                  string p = (string) per. Current;                  Console.WriteLine (P);}}}  

The result is the same:


We found in the string view definition that string inherits from the IEnumerable interface, there is only one method GetEnumerator () in the IEnumerable interface, (the method has been implemented in the String Class), and the function of the method is to Returns an enumerator that iterates through the collection IEnumerator, as we define in the IEnumerator, it is also an interface that has only three declarations of methods, current (gets the present element in the collection), MoveNext (advances the enumerator to the next element of the collection, Successful return true, which returns false over the end, reset (sets the enumerator to its initial position, which precedes the first element in the collection), i.e., if the GetEnumerator method is not implemented in our custom class, and the current, MoveNext method, you cannot traverse using a foreach statement.

The foreach statement traverses the custom class:

It is also an example of the above movie theater, but this time we do not need for a for loop output, but to implement the foreach statement traversal output, as follows:

Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text; Using System.Collections; Adding this is necessary namespace Test1 {//define Cinema Inheritance IEnumerable interface Implementation GetEnumerator () function class Cinema:ienumerable {//define a two-dimensional number        Group Private string[,] seat = new string[5, 5];      Define seat number static public int index=-1;              Define a two-dimensional indexer public string this[uint A, uint b] {get {return seat[a, b];} set {seat[a, b] = value;}               The set accessor comes with the value parameter}//implements the GetEnumerator method public IEnumerator GetEnumerator () { return new IEnumerator (seat);          Using the constructor method to pass in the seat parameter}//due to the need for the above return value, inherit the interface IEnumerator and implement the method private class Ienumerator:ienumerator                  {private string[,] seats;//assigns the incoming seat array to it public IEnumerator (string[,] s) {               Seats = s; }//define current read-only property public OBject Current {//calculates the coordinates of the array according to the seat number, i.e. the physical location get {return seats[1+ (INDEX/4), (index%4) +1];} }//define rules to move down public bool MoveNext () {index+ +;                  Index the position of the next seat number if (index <=) {return true;                            } else return false;                                         }//Because this program is not used in this method is not implemented, but must be written otherwise will error public void Reset () {          }}} class program {static void Main (string[] args)  {Cinema movieroom = new Cinema ();//Instantiate//for Circular index write for (UINT i = 1; i < 5;  i++) {for (UINT j = 1; j < 5; J + +) {movieroom[i,                  J] = "First" + i + "row" + j + "column";        }      }//Call the foreach statement to traverse the output foreach (string i in Movieroom) {CONSOLE.WR                                Iteline (i+ "\ T" + (CINEMA.INDEX+1) + "number"); }          }      }  }

Results:

The result is the same ....

The above is the C # learning diary----Two-dimensional indexer and the content of the foreach traversal indexer, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.