Represents the method that performs an action on the specified object.
Remarks
This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.
Note:
In addition to displaying the contents using the Print method, the C# example also demonstrates the use of Anonymous Methods (C# Programming Guide) to display the contents to the console.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
// Display the contents of the List out using the "Print" delegate.
Console.WriteLine("Using Action ");
names.ForEach(Print);
// The following demonstrates the Anonymous Delegate feature of C#
// to display the contents of the List to the console.
Console.WriteLine("Using Anonymous Delegate feature");
names.ForEach(
delegate(String name){
Console.WriteLine(name);
}
);
Console.Read();
}
private static void Print(string s)
{
Console.WriteLine(s);
}
}
using System.Collections.Generic;
class Program
{
static void Main()
{
List<String> names = new List<String>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
// Display the contents of the List out using the "Print" delegate.
Console.WriteLine("Using Action
names.ForEach(Print);
// The following demonstrates the Anonymous Delegate feature of C#
// to display the contents of the List to the console.
Console.WriteLine("Using Anonymous Delegate feature");
names.ForEach(
delegate(String name){
Console.WriteLine(name);
}
);
Console.Read();
}
private static void Print(string s)
{
Console.WriteLine(s);
}
}
No comments:
Post a Comment