Implement the foreach function in C #

Source: Internet
Author: User
1. mysplit class

///   <Summary>
/// Mysplit class
///   </Summary>
Public   Class Mysplit: ienumerable
{
Private   String [] Elements;

Public mysplit ( string source, char [] delimiters)
{< br> elements
= source. split (delimiters);
}

Ienumerator ienumerable. getenumerator ()
{
Return NewMyenumerator (This);
}

# Region Implement the ienumerator interface in the nested class
///   <Summary>
/// Implement the ienumerator interface in the nested class to facilitate the creation of multiple enumerations in the future
///   </Summary>
Public   Class Myenumerator: ienumerator
{
Private   Int Position =   - 1 ;
Private Mysplit T;

PublicMyenumerator (mysplit T)
{
This. T=T;
}

Public   Bool Movenext ()
{
If (Position < T. elements. Length -   1 )
{
Position
++ ;
Return   True ;
}
Else
{
Return   False ;
}
}

Public VoidReset ()
{
Position
= -1;
}

Object Ienumerator. Current
{
Get
{
Try
{
Return T. elements [position];
}
Catch (Indexoutofrangeexception)
{
Throw   New Invalidoperationexception ();
}
}
}
}
# Endregion
}

2. Use

Mysplit =   New Mysplit ( " Soybean boys: I love you! " , New   Char [] { '   ' , ' - ' });
Foreach ( String Item In Mysplit)
{
Console. writeline (item );
}

3. output results
Soybean boys:
I
Love
You!

RelatedArticle: Implement index indicator in C #

Address: http://www.cnblogs.com/anjou/archive/2007/07/05/807357.html

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.