委托-C#
1.Action委托:无返回值,但可以有参数。注:不用显示定义委托,参考https://msdn.microsoft.com/zh-cn/library/dd269635(v=vs.110).aspx
1 using System; 2 using System.IO; 3 4 delegate void ConcatStrings(string string1, string string2); 5 6 public class TestDelegate 7 { 8 public static void Main() 9 { 10 string message1 = "The first line of a message."; 11 string message2 = "The second line of a message."; 12 ConcatStrings concat; 13 14 if (Environment.GetCommandLineArgs().Length > 1) 15 concat = WriteToFile; 16 else 17 concat = WriteToConsole; 18 19 concat(message1, message2); 20 } 21 22 private static void WriteToConsole(string string1, string string2) 23 { 24 Console.WriteLine("{0}\n{1}", string1, string2); 25 } 26 27 private static void WriteToFile(string string1, string string2) 28 { 29 StreamWriter writer = null; 30 try 31 { 32 writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false); 33 writer.WriteLine("{0}\n{1}", string1, string2); 34 } 35 catch 36 { 37 Console.WriteLine("File write operation failed..."); 38 } 39 finally 40 { 41 if (writer != null) writer.Close(); 42 } 43 } 44 }
1 using System; 2 using System.IO; 3 4 public class TestAction2 5 { 6 public static void Main() 7 { 8 string message1 = "The first line of a message."; 9 string message2 = "The second line of a message."; 10 Action<string, string> concat; 11 12 if (Environment.GetCommandLineArgs().Length > 1) 13 concat = WriteToFile; 14 else 15 concat = WriteToConsole; 16 17 concat(message1, message2); 18 } 19 20 private static void WriteToConsole(string string1, string string2) 21 { 22 Console.WriteLine("{0}\n{1}", string1, string2); 23 } 24 25 private static void WriteToFile(string string1, string string2) 26 { 27 StreamWriter writer = null; 28 try 29 { 30 writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false); 31 writer.WriteLine("{0}\n{1}", string1, string2); 32 } 33 catch 34 { 35 Console.WriteLine("File write operation failed..."); 36 } 37 finally 38 { 39 if (writer != null) writer.Close(); 40 } 41 } 42 }
1 using System; 2 using System.IO; 3 4 public class TestAnonymousMethod 5 { 6 public static void Main() 7 { 8 string message1 = "The first line of a message."; 9 string message2 = "The second line of a message."; 10 Action<string, string> concat; 11 12 if (Environment.GetCommandLineArgs().Length > 1) 13 concat = delegate(string s1, string s2) { WriteToFile(s1, s2); }; 14 else 15 concat = delegate(string s1, string s2) { WriteToConsole(s1, s2);} ; 16 17 concat(message1, message2); 18 } 19 20 private static void WriteToConsole(string string1, string string2) 21 { 22 Console.WriteLine("{0}\n{1}", string1, string2); 23 } 24 25 private static void WriteToFile(string string1, string string2) 26 { 27 StreamWriter writer = null; 28 try 29 { 30 writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false); 31 writer.WriteLine("{0}\n{1}", string1, string2); 32 } 33 catch 34 { 35 Console.WriteLine("File write operation failed..."); 36 } 37 finally 38 { 39 if (writer != null) writer.Close(); 40 } 41 } 42 }
1 using System; 2 using System.IO; 3 4 public class TestLambdaExpression 5 { 6 public static void Main() 7 { 8 string message1 = "The first line of a message."; 9 string message2 = "The second line of a message."; 10 Action<string, string> concat; 11 12 if (Environment.GetCommandLineArgs().Length > 1) 13 concat = (s1, s2) => WriteToFile(s1, s2); 14 else 15 concat = (s1, s2) => WriteToConsole(s1, s2); 16 17 concat(message1, message2); 18 } 19 20 private static void WriteToConsole(string string1, string string2) 21 { 22 Console.WriteLine("{0}\n{1}", string1, string2); 23 } 24 25 private static void WriteToFile(string string1, string string2) 26 { 27 StreamWriter writer = null; 28 try 29 { 30 writer = new StreamWriter(Environment.GetCommandLineArgs()[1], false); 31 writer.WriteLine("{0}\n{1}", string1, string2); 32 } 33 catch 34 { 35 Console.WriteLine("File write operation failed..."); 36 } 37 finally 38 { 39 if (writer != null) writer.Close(); 40 } 41 } 42 }
2.Func:必有返回值,可以一个或者多个参数,注不用显示定义委托,来源于https://msdn.microsoft.com/zh-cn/library/bb534647(v=vs.110).aspx
1 using System; 2 3 delegate string[] ExtractMethod(string stringToManipulate, int maximum); 4 5 public class DelegateExample 6 { 7 public static void Main() 8 { 9 // Instantiate delegate to reference ExtractWords method 10 ExtractMethod extractMeth = ExtractWords; 11 string title = "The Scarlet Letter"; 12 // Use delegate instance to call ExtractWords method and display result 13 foreach (string word in extractMeth(title, 5)) 14 Console.WriteLine(word); 15 } 16 17 private static string[] ExtractWords(string phrase, int limit) 18 { 19 char[] delimiters = new char[] {' '}; 20 if (limit > 0) 21 return phrase.Split(delimiters, limit); 22 else 23 return phrase.Split(delimiters); 24 } 25 }
1 using System; 2 3 public class GenericFunc 4 { 5 public static void Main() 6 { 7 // Instantiate delegate to reference ExtractWords method 8 Func<string, int, string[]> extractMethod = ExtractWords; 9 string title = "The Scarlet Letter"; 10 // Use delegate instance to call ExtractWords method and display result 11 foreach (string word in extractMethod(title, 5)) 12 Console.WriteLine(word); 13 } 14 15 private static string[] ExtractWords(string phrase, int limit) 16 { 17 char[] delimiters = new char[] {' '}; 18 if (limit > 0) 19 return phrase.Split(delimiters, limit); 20 else 21 return phrase.Split(delimiters); 22 } 23 }
1 using System; 2 3 public class LambdaExpression 4 { 5 public static void Main() 6 { 7 char[] separators = new char[] {' '}; 8 Func<string, int, string[]> extract = (s, i) => 9 i > 0 ? s.Split(separators, i) : s.Split(separators) ; 10 11 string title = "The Scarlet Letter"; 12 // Use Func instance to call ExtractWords method and display result 13 foreach (string word in extract(title, 5)) 14 Console.WriteLine(word); 15 } 16 } 17 18 19 using System; 20 using System.Collections.Generic; 21 using System.Linq; 22 23 public class Func3Example 24 { 25 public static void Main() 26 { 27 Func<String, int, bool> predicate = (str, index) => str.Length == index; 28 29 String[] words = { "orange", "apple", "Article", "elephant", "star", "and" }; 30 IEnumerable<String> aWords = words.Where(predicate).Select(str => str); 31 32 foreach (String word in aWords) 33 Console.WriteLine(word); 34 } 35 }
3.Delegate: 可以有参数,也可以有返回值。表示委托,委托是一种数据结构,它引用静态方法或引用类实例及该类的实例方法。来源于https://msdn.microsoft.com/zh-cn/library/system.delegate(v=vs.110).aspx
1 using System; 2 public class SamplesDelegate { 3 4 // Declares a delegate for a method that takes in an int and returns a String. 5 public delegate String myMethodDelegate( int myInt ); 6 7 // Defines some methods to which the delegate can point. 8 public class mySampleClass { 9 10 // Defines an instance method. 11 public String myStringMethod ( int myInt ) { 12 if ( myInt > 0 ) 13 return( "positive" ); 14 if ( myInt < 0 ) 15 return( "negative" ); 16 return ( "zero" ); 17 } 18 19 // Defines a static method. 20 public static String mySignMethod ( int myInt ) { 21 if ( myInt > 0 ) 22 return( "+" ); 23 if ( myInt < 0 ) 24 return( "-" ); 25 return ( "" ); 26 } 27 } 28 29 public static void Main() { 30 31 // Creates one delegate for each method. For the instance method, an 32 // instance (mySC) must be supplied. For the static method, use the 33 // class name. 34 mySampleClass mySC = new mySampleClass(); 35 myMethodDelegate myD1 = new myMethodDelegate( mySC.myStringMethod ); 36 myMethodDelegate myD2 = new myMethodDelegate( mySampleClass.mySignMethod ); 37 38 // Invokes the delegates. 39 Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 5, myD1( 5 ), myD2( 5 ) ); 40 Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", -3, myD1( -3 ), myD2( -3 ) ); 41 Console.WriteLine( "{0} is {1}; use the sign \"{2}\".", 0, myD1( 0 ), myD2( 0 ) ); 42 } 43 44 }
4.EventHandler:表示将处理不包含事件数据的事件的方法。来源于https://msdn.microsoft.com/zh-cn/library/system.eventhandler(v=vs.110).aspx
1 using System; 2 3 namespace ConsoleApplication1 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Counter c = new Counter(new Random().Next(10)); 10 c.ThresholdReached += c_ThresholdReached; 11 12 Console.WriteLine("press 'a' key to increase total"); 13 while (Console.ReadKey(true).KeyChar == 'a') 14 { 15 Console.WriteLine("adding one"); 16 c.Add(1); 17 } 18 } 19 20 static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e) 21 { 22 Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached); 23 Environment.Exit(0); 24 } 25 } 26 27 class Counter 28 { 29 private int threshold; 30 private int total; 31 32 public Counter(int passedThreshold) 33 { 34 threshold = passedThreshold; 35 } 36 37 public void Add(int x) 38 { 39 total += x; 40 if (total >= threshold) 41 { 42 ThresholdReachedEventArgs args = new ThresholdReachedEventArgs(); 43 args.Threshold = threshold; 44 args.TimeReached = DateTime.Now; 45 OnThresholdReached(args); 46 } 47 } 48 49 protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) 50 { 51 EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached; 52 if (handler != null) 53 { 54 handler(this, e); 55 } 56 } 57 58 public event EventHandler<ThresholdReachedEventArgs> ThresholdReached; 59 } 60 61 public class ThresholdReachedEventArgs : EventArgs 62 { 63 public int Threshold { get; set; } 64 public DateTime TimeReached { get; set; } 65 } 66 }