using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { delegate string UppercaseDelegate(string input); static string UppercaseFirst(string input) { char[] buffer = input.ToCharArray(); buffer[0] = char.ToUpper(buffer[0]); return new string(buffer); } static string UppercaseLast(string input) { char[] buffer = input.ToCharArray(); buffer[buffer.Length - 1] = char.ToUpper(buffer[buffer.Length - 1]); return new string(buffer); } static string UppercaseAll(string input) { return input.ToUpper(); } static void WriteOutput(string input, UppercaseDelegate del) { Console.WriteLine("Your string before: {0}", input); Console.WriteLine("Your string after: {0}", del(input)); } static void Main(string[] args) { // Wrap the methods inside delegate instances and pass to the method. WriteOutput("perls", new UppercaseDelegate(UppercaseFirst)); WriteOutput("perls", new UppercaseDelegate(UppercaseLast)); WriteOutput("perls", new UppercaseDelegate(UppercaseAll)); UppercaseDelegate d=delegate(string s){ return s.ToUpper(); }; WriteOutput(" UppercaseDelegate d=delegate(string s)",d); //Anonymous methods WriteOutput("DDDD", delegate(string s) { return s.ToLower(); }); //lambda expression WriteOutput("FFFF",new UppercaseDelegate(x=>x.ToLower())); /* Using lambda expressions */ // // Use implicitly typed lambda expression. // ... Assign it to a Func instance. // Func<int, int> func1 = x => x + 1; // // Use lambda expression with statement body. // Func<int, int> func2 = x => { return x + 1; }; // // Use formal parameters with expression body. // Func<int, int> func3 = (int x) => x + 1; // // Use parameters with a statement body. // Func<int, int> func4 = (int x) => { return x + 1; }; // // Use multiple parameters. // Func<int, int, int> func5 = (x, y) => x * y; // // Use no parameters in a lambda expression. // Action func6 = () => Console.WriteLine(" Use no parameters in a lambda expression"); // // Use delegate method expression. // Func<int, int> func7 = delegate(int x) { return x + 1; }; // // Use delegate expression with no parameter list. // Func<int> func8 = delegate { return 1 + 1; }; // // Invoke each of the lambda expressions and delegates we created. // ... The methods above are executed. // Console.WriteLine(func1.Invoke(1)); Console.WriteLine(func2.Invoke(1)); Console.WriteLine(func3.Invoke(1)); Console.WriteLine(func4.Invoke(1)); Console.WriteLine(func5.Invoke(2, 2)); func6.Invoke(); Console.WriteLine(func7.Invoke(1)); Console.WriteLine(func8.Invoke()); Console.ReadLine(); } } }
C# Delegate ,Anonymous methods,lambda expression
最新推荐文章于 2024-10-03 07:17:26 发布