How to support foreach in C #

zhaozj2021-02-08  226

In VB6, I like the for EACH statement and let my class support this feature. I also hope that there is this feature in C #, one checks, and I will find that C # support forcach, I have to introduce anything that makes yourself. Support for foreach. Still look at MSDN.

MSDN pointed to the system.collections.ienumerable interface, and only one method in the IENUMERABLE interface: GetENUMERATOR, he asked to return to the object reference to the System.Collections.ienumerator interface, see the Ienumerator interface, I understand the working principle, he has MoveNext , Reset method and Current property.

Honestly, I really don't understand why MS is not directly supporting the Ienumerator interface. Why do you want to be bent, then you think about it, it is really reasonable, told me that I said that I said that it is roughly. Provide multiple status under multithreading, don't know right, anyway, I think so.

Look at the demo code I wrote:

Using system;

Namespace WindowsApplication3

{

Public Class Class1

{

[Stathread]

Static void main ()

{

Demo d = new demo ();

// foreach demo code

Foreach (Int I in D)

Console.writeLine (i);

}

}

///

Support Foreach demonstration class

Public class demo: system.collections.ienumerable

{

/ / Internal to enumerate data

int [] Intlist = {1, 2, 3};

PUBLIC DEMO () {}

// Object supports the IENUMERABLE interface, returns an instance that supports the Ienumerator interface

Public system.collections.ienumerator geteNumerator ()

{

DemOForienumerator D = New DemoForienumerator (this);

Return D;

}

// Index, start the index from 1

Public int this [int nindex]

{

Get {return Intlist [NINDEX-1];

}

//total

Public int LENGTH

{

Get {return Intlist.Length;}

}

}

///

Supports the class of the IEnumerator interface

Class demoForienumerator: system.collections.ienumerator

{

Demo MDemo;

INT per = 0;

Public DemoForienumerator (Demo D)

{mdemo = d;

// Move forward, return false when you can't continue to move, otherwise returns True.

Public system.Boolean MoveNext ()

{

IF (per> = mdemo.length)

Return False;

Else

{

PER ;

Return True;

}

}

// Reset

Public void reset ()

{PER = 0;}

// The value under the current pointer is.

Public Object Current

{

Get {return mdemo [per];

}

}

}

转载请注明原文地址:https://www.9cbs.com/read-2582.html

New Post(0)