namespace ConsoleApplication1 { public delegate void methodDelegate(string str); class Program { static void Main(string[] args) { Student student = new Student(); Teacher teacher = new Teacher("王老師"); methodDelegate methodDelegate1 = new methodDelegate(student.getStudentName); methodDelegate1 += teacher.getTeacherName; //可以指向不同類中的方法! //methodDelegate1 += teacher.getClassName; 指向簽名不符的方法時提示錯誤! methodDelegate1.Invoke("張三"); Console.ReadLine(); } } class Student { private String name = ""; public Student (String _name) { this.name = _name ; } public Student() {} public void getStudentName(String _name) { if (this.name != "" ) Console.WriteLine("Student's name is {0}", this.name); else Console.WriteLine("Student's name is {0}", _name); } } class Teacher { private String name; public Teacher(String _name) { this.name = _name; } public void getTeacherName(String _name) { if (this.name != "") Console.WriteLine("Teacher's name is {0}", this.name); else Console.WriteLine("Teacher's name is {0}", _name); } public string getClassName() { return "Eanlish"; } } }
上面代碼中實現對委托的調用
最後將被調用的委托輸出
private delegate String getAString( string parament); static void Main(String []args) { int temp = 40; getAString stringMethod = new getAString(temp.ToString); //傳遞temp.ToString調用委托
Console.WriteLine("String is {0}", stringMethod()); //stringMethod()調用已經接受參數的委托 Console.ReadLine(); }
getAString stringMethod = new getAString(temp.ToString); stringMethod += temp.ToString; stringMethod -= temp.ToString;
這種調用之後,按照接受參數的次數, 委托會生成一個列表,每用+=調用一次,會增加一個列表項,-=調用一次,會移除一個列表項。
當我們定義委托 讓委托形成一個數組的時候,我們可以通過遍歷數組的方式來調用它
delegate double Operations(double x); class Program { static void Main() { Operations[] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; for (int i = 0; i < operations.Length; i++) { Console.WriteLine("Using operations[{0}]:", i); DisplayNumber(operations[i], 2.0); DisplayNumber(operations[i], 7.94); Console.ReadLine(); } } static void DisplayNumber(Operations action, double value) { double result = action(value); Console.WriteLine( "Input Value is {0}, result of operation is {1}", value, result); } } struct MathOperations { public static double MultiplyByTwo(double value) { return value * 2; } public static double Square(double value) { return value * value; } }
上面實例中
將委托定義好
之後就可以遍歷它
委托的實現方式還有三種 持續更新中!