Now I want to talk about containers in C #. This is a very important topic, because no matter what kind of program you write, you cannot deal with the container. What is a container (pour!). A container is something that can hold something (again!), in C # and Java, an object-oriented programming language, a container is called an object that can hold objects, not saying "is everything an object?" Previously, I was a C + + programmer friend told me that the container in Java is too good to use, more useful than C + +. But as Java's later C # undoubtedly, its container function is certainly very powerful.
The foreach statement is the simplest way to traverse the elements of a container. We can use the System.Collections.IEnumerator class and the System.Collections.IEnumerable interface to work with containers in C #, Here's an example of a string splitter.
From://Collectionclasses\tokens.cs
001:using System;
002:using System.Collections;
003:
004:public class Tokens:ienumerable
005: {
006:private string[] elements;
007:
008:tokens (string source, char[] delimiters)
009: {
010:elements = source. Split (delimiters);
011:}
012:
013://reference IEnumerable interface 014:
015:public IEnumerator GetEnumerator ()
016: {
017:return New Tokenenumerator (this);
018:}
019:
020:
021:
022:private class Tokenenumerator:ienumerator
023: {
024:private int position =-1;
025:private Tokens t;
026:
027:public tokenenumerator (Tokens t)
028: {
029:THIS.T = t;
030:}
031:
032:public bool MoveNext ()
033: {
034:if (Position < t.elements.length-1)
035: {
036:position++;
037:return true;
038:}
039:else
040: {
041:return false;
042:}
043:}
044:
045:public void Reset ()
046: {
047:position =-1;
048:}
049:
050:public Object Current
051: {
052:get
053: {
054:return T.elements[position];
055:}
056:}
057:}
058:
059://Test 060:
061:static void Main ()
062: {
063:tokens f = new Tokens ("This was a well-done program.", new char[] {', '-'});
064:foreach (string item in F)
065: {
066:console.writeline (item);
067:}
068:}
069:}
The output of this example is:
This
Is
A
Well
Done
Program.
The above is the Sunwen tutorial----C # Advanced (10) content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!