Search C # (Statement 3) C # (QQ: 249178521)
9.FOR statement
· For statement
The variable declared in the W for block is partial, only valid in the FOR block.
w can omit any part of the for statement
For (int digit = 0; DIGIT! = 10; Digit )
{
Console.write ("{0}", DIGIT;
}
// Show 0 1 2 3 4 5 6 7 8 9 on the screen
Variables declared in the For block are only valid in the FOR block. E.g:
For (int digit = 0; DIGIT! = 10; Digit )
{...}
Console.writeline (DIGIT); / / Error, DIGIT is only valid in the FOR block
You can declare multiple variables and multiple variation statements by commas in the for statement:
For (int i = 0, j = 0; i j <20; i , j )
{...}
10.Foreach
· From SHELL, VB, Perl
W is used for either collection, including arrays
Using system;
Sealed Class Foreach
{
Static void
Main
(String [] ARGS)
{
FOREACH (String Arg In Args)
{
Console.write ("{0}", arg);
}
Console.writeLine ();
}
}
Compile the above programs in the Windows command line: C: / sharp> CSC foreach.cs
Then type: c: c: / sharp> foreach 0 1 2 3 4 5 6 7 8 9
Show 0 1 2 3 4 5 6 7 8 9
Foreach is used to traverse the elements in the collection or array.
11. What kind of attention of manufacta
FOREACH (Type Identifier In Expressions)
W type and identifier declare a loop variable
W Cycle variable is implied as readonly, can't have REF or OUT modification
W Expression is a collection of available
Sealed Class ForeachTranslation
{
Static void Example (MywibbleCollection Wibbles)
{
Myenumerator POS = Wibbles.Getenumerator ();
While (pos.movenext ())
{
WIBBLE CURRENT = POS.CURRENT;
Console.write ("{0}", current);
}
}
}
Definition rules for collection type: (Suppose the name of the collection is C)
C must define a public function getEnumerator (), the return value of this function is a structure type or a type of type or an interface type (assuming the name of the return value is e);
Return the definition rule of Value E:
ü E contains a public function MoveNext (), used to make the next element in the collection, the type of return value is BOOL.
ü E contains a public attribute Current to read the current value. The type of this attribute is the type of collection element.
12.Break / Continue
BREAK is used to end a loop, and Continue is used to restart a loop.
13. Find the wrong
{
For (int i = 0; I! = 12; i ) 1 {
...
}
INT i = 0;
}
For (int i = 0, i == 12, i ) 2
{
...
}
Foreach (Int I in Array) 3
{
i ;
}
Error of the first program: Variables that cannot be declared in a parent block and a sub-block
Error of the second program: not using a comma to split the three parts of the For statement, but the semicolon should be used.
The judgment condition for the for statement should be a logical statement.
Error of the third program: Foreach's loop variable is read-only