C# //Pre-test Loops: while (i < 10)
i++;
for (i = 2; i < = 10; i += 2)
System.Console.WriteLine(i);
//Post-test Loop:
do
i++;
while (i < 10);
// Array or collection looping
string[] names = {"Steven", "SuOk", "Sarah"};
foreach (string s in names)
System.Console.WriteLine(s);
Arrays
VB.NET
Dim nums() As Integer = {1, 2, 3}
For i As Integer = 0 To nums.Length - 1
Console.WriteLine(nums(i))
Next
'4 is the index of the last element, so it holds 5 elements
Dim names(4) As String
names(0) = "Steven"
'Throws System.IndexOutOfRangeException
names(5) = "Sarah"
'Resize the array, keeping the existing
'values (Preserve is optional)
ReDim Preserve names(6)
Dim twoD(rows-1, cols-1) As Single
twoD(2, 0) = 4.5
Dim jagged()() As Integer = { _
New Integer(4) {}, New Integer(1) {}, New Integer(2) {} }
jagged(0)(4) = 5
C#
int[] nums = {1, 2, 3};
for (int i = 0; i < nums.Length; i++)
Console.WriteLine(nums[i]);
// 5 is the size of the array
string[] names = new string[5];
names[0] = "Steven";
// Throws System.IndexOutOfRangeException
names[5] = "Sarah"
// C# can't dynamically resize an array.
//Just copy into new array.
string[] names2 = new string[7];
// or names.CopyTo(names2, 0);
Array.Copy(names, names2, names.Length);
float[,] twoD = new float[rows, cols];
twoD[2,0] = 4.5;
int[][] jagged = new int[3][] {
new int[5], new int[2], new int[3] };
jagged[0][4] = 5;
Functions
VB.NET
'Pass by value (in, default), reference
'(in/out), and reference (out)
Sub TestFunc(ByVal x As Integer, ByRef y As Integer,
ByRef z As Integer)
x += 1
y += 1
z = 5
End Sub
'c set to zero by default
Dim a = 1, b = 1, c As Integer
TestFunc(a, b, c)
System.Console.WriteLine("{0} {1} {2}", a, b, c) '1 2 5
'Accept variable number of arguments
Function Sum(ByVal ParamArray nums As Integer()) As Integer
Sum = 0
For Each i As Integer In nums
Sum += i
Next
End Function 'Or use a Return statement like C#
Dim total As Integer = Sum(4, 3, 2, 1) 'returns 10
'Optional parameters must be listed last
'and must have a default value
Sub SayHello(ByVal name As String,
Optional ByVal prefix As String = "")
System.Console.WriteLine("Greetings, " & prefix
& " " & name)
End Sub
SayHello("Steven", "Dr.")
SayHello("SuOk")
上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 下一页
|