首页 > 代码库 > CLR Via CSharp----------Delegate&Lambda

CLR Via CSharp----------Delegate&Lambda

CLR Via CSharp----------Delegate&Lambda

 

1. There are some simple samples of how to use the delegate。

 1     class Program 2     { 3         static void Main(string[] args) 4         { 5  6             String[] names = { }; 7  8             Counter(1, 3, null); 9             Counter(1, 4, Conso);10             Counter(1, 4, Mess);11 12             Program p = new Program();13             Counter(1, 4, new FeedBack(p.Conso2));14 15             FeedBack f1 = new FeedBack(Conso);16             FeedBack f2 = new FeedBack(Mess);17 18             FeedBack f = null;19             f += f1;20             f += f2;21             Counter(1, 30, f);22         }23 24         private static void Counter(int from, int to, FeedBack fb)25         {26             for (int i = from; i < to; i++)27                 if (fb != null)28                     fb(i);29         }30 31         private static void Conso(int value)32         {33             Console.WriteLine("Item=" + value.ToString());34         }35 36         private void Conso2(int value)37         {38             Console.WriteLine("Item=" + value.ToString());39         }40 41         private static void Mess(int value)42         {43             MessageBox.Show("Item=" + value.ToString());44         }45 46         private void Mess2(int value)47         {48             MessageBox.Show("Item=" + value.ToString());49         }50     }

2. There are much better practices.

1             String[] names = { "Jeff", "Kristin", "Aidan", "Grant", "HaifengCai" };2             Char charToEnd = a;3             names = Array.FindAll(names, name => name.IndexOf(charToEnd) >= 0);4             names = Array.ConvertAll(names, name => name.ToUpper());5             Array.ForEach(names, Console.WriteLine);

 

CLR Via CSharp----------Delegate&Lambda