using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; //線程類:暫停函數 namespace Program { class Program { static void Main(string[] args) { //方法1: //Action<Student> callback = ((Student st) => { Console.WriteLine(st.Name); });//lambda 表達式 //方法3: Action<Student> callback = ShowName; Thread th = new Thread(Fun); th.IsBackground = true; th.Start(callback); Console.ReadKey(); } private static void Fun(object obj) { for (int i = 1; i <= 10; i++) { Console.WriteLine("子線程循環操作第 {0} 次", i); Thread.Sleep(500); } Action<Student> callback = obj as Action<Student>; Student st = new Student(); st.ID = 1; st.Name = "Long"; st.Age = 20; callback(st); } //方法2:上面的Lambda表達式也可以回城匿名函數 private static Action<Student> callback = delegate(Student st) { Console.WriteLine(st.Name); }; //方法3: private static void ShowName(Student st) { Console.WriteLine(st.Name); } } }
其中,Student類的定義如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Program { public class Student { public int ID; public string Name; public int Age; } }