(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
An Action triggered by Array.ForEach
using System;
class MyClass {
public int i;
public MyClass(int x) {
i = x;
}
}
class MainClass {
static void show(MyClass o) {
Console.Write(o.i + " ");
}
public static void Main() {
MyClass[] nums = new MyClass[5];
nums[0] = new MyClass(5);
nums[1] = new MyClass(2);
nums[2] = new MyClass(3);
nums[3] = new MyClass(4);
nums[4] = new MyClass(1);
Console.Write("Contents of nums: ");
// Use action to show the values.
Array.ForEach(nums, MainClass.show);
Console.WriteLine();
}
}
Contents of nums: 5 2 3 4 1
Array.ForEach with a delegate
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
public class MainClass
{
public static void Main()
{
int[] array = new int[] { 8, 2, 3, 5, 1, 3 };
Array.ForEach<int>(array, delegate(int x) { Console.Write(x + " "); });
Console.WriteLine();
}
}
8 2 3 5 1 3
foreach with Arrays
class MainClass
{
static void Main()
{
int[] array = new int[]{1, 2, 3, 4, 5, 6};
foreach (int item in array)
{
System.Console.WriteLine(item);
}
}
}
Use an Action to change the values
using System;
class MyClass {
public int i;
public MyClass(int x) {
i = x;
}
}
class MainClass {
static void neg(MyClass o) {
o.i = -o.i;
}
public static void Main() {
MyClass[] nums = new MyClass[5];
nums[0] = new MyClass(5);
nums[1] = new MyClass(2);
nums[2] = new MyClass(3);
nums[3] = new MyClass(4);
nums[4] = new MyClass(1);
// Use action to negate the values.
Array.ForEach(nums, MainClass.neg);
}
}