В. В. Подбельский Иллюстрации к курсу лекций по дисциплине «Программирование» С#_15 Delegates Использованы материалы пособия Daniel Solis, Illustrated C# 2008. Делегаты
15 -1. What Is a Delegate?
15 -2. Declaring the Delegate Type Keyword Delegate type name ↓ ↓ delegate void My. Del ( int x );
15 -3. Делегат-тип и экземпляр делегата
15 -4. Creating the Delegate Object Объявление ссылки: Delegate type Variable ↓ ↓ My. Del del. Var; Создание экземпляров делегата: Instance method ↓ del. Var = new My. Del( my. Inst. Obj. My. M 1 ); d. Var = new My. Del( SClass. Other. M 2 ); ↑ Static method Упрощенный синтаксис: del. Var = my. Inst. Obj. My. M 1; // Create delegate and save reference. d. Var = SClass. Other. M 2; // Create delegate and save reference.
15 -5. Instantiating the delegates
15 -6. Assigning Delegates My. Del del. Var; del. Var = my. Inst. Obj. My. M 1; // Create and assign the delegate object. . del. Var = SClass. Other. M 2; // Create and assign the new delegate object.
15 -7. Combining Delegates My. Del del. A = my. Inst. Obj. My. M 1; My. Del del. B = SClass. Other. M 2; My. Del del. C = del. A + del. B; // Has combined invocation list
15 -8. Adding Methods to Delegates My. Del del. Var = inst. My. M 1; // Create and initialize. del. Var += SCl. m 3; // Add a method. del. Var += X. Act; // Add a method
15 -9. Removing Methods from a Delegate del. Var -= SCl. m 3; // Remove the method from the delegate.
15 -10. Invoking a Delegate My. Del del. Var = inst. My. M 1; del. Var += SCl. m 3; del. Var += X. Act; . . . del. Var( 55 ); // Invoke the delegate.
15 -11. Пример – делегат и класс // Define a delegate type with no return value and no parameters. delegate void Print. Function(); class Test { public void Print 1() { Console. Write. Line("Print 1 -- instance"); } public static void Print 2() { Console. Write. Line("Print 2 -- static"); } }
15 -12. Применение делегата class Program { static void Main() { Test t = new Test(); // Create a test class instance. Print. Function pf; // Create a null delegate. pf = t. Print 1; // Instantiate and initialize the delegate // Add three more methods to the delegate. pf += Test. Print 2; pf += t. Print 1; pf += Test. Print 2; // The delegate now contains four methods. if( null != pf ) // Make sure the delegate has methods. pf(); // Invoke the delegate. else Console. Write. Line("Delegate is empty"); } }
15 -13. Invoking Delegates with Return Values delegate int My. Del( ); // Declare method with return valu class My. Class { int Int. Value = 5; public int Add 2() { Int. Value += 2; return Int. Value; } public int Add 3() { Int. Value += 3; return Int. Value; } }
15 -14. Invoking Delegates with Return Values class Program { static void Main( ) { My. Class mc = new My. Class(); My. Del m. Del = mc. Add 2; // Create and initialize the dele m. Del += mc. Add 3; // Add a method. m. Del += mc. Add 2; // Add a method. // Invoke the delegate and use the return value: Console. Write. Line("Value: {0}", m. Del () ); }↑ } This code produces the following output: Value: 12
15 -15. Схема к примеру
15 -16. Invoking Delegates with Reference Parameters delegate void My. Del( ref int X ); class My. Class { public void Add 2(ref int x) { x += 2; } public void Add 3(ref int x) { x += 3; } static void Main() { My. Class mc = new My. Class(); My. Del m. Del = mc. Add 2; m. Del += mc. Add 3; m. Del += mc. Add 2; int x = 5; m. Del(ref x); Console. Write. Line("Value: {0}", x); } }
15 -17. Схема к примеру
15 -a. Два свойства делегатов public delegate int[ ] Row(int num); // делегат-тип public class Example { // Метод возвращает массив цифр целого числа-параметра: static public int[ ] series(int num) {…………………} ………. . } // End of Example class Program { static void Main() { Row del. Row; // Ссылка на делегат del. Row = new Row(Example. series); // Экземпляр делегата …………………. Console. Write. Line("del. Row is equals {0}. ", del. Row. Method); Console. Write. Line("del. Row. Target is equals {0}. ", del. Row. Target); } } Результат выполнения этих операторов: del. Row is equals Int 32[ ] series(Int 32) del. Row. Target is equals
15 -b. Массивы делегатов delegate void Steps(); // делегат-тип class Robot { // класс для представления робота int x, y; // положение робота на плоскости public void right() { x++; } // направо public void left() { x--; } // налево public void forward() { y++; } // вперед public void backward() { y--; } // назад public void position() // сообщить координаты { Console. Write. Line("The Robot position: x={0}, y={1}", x, y); } }
15 -c. Массивы делегатов class Program { static void Main() { Robot rob = new Robot(); // конкретный робот Steps[ ] trace = { new Steps(rob. backward), new Steps(rob. left)}; for (int i = 0; i < trace. Length; i++) { Console. Write. Line("Method={0}, Target={1}", trace[i]. Method, trace[i]. Target); trace[i](); } rob. position(); // сообщить координаты } } Результат выполнения программы: Method=Void backward(), Target=Robot Method=Void left(), Target=Robot The Robot position: x=-1, y=-2
15 -18. Anonymous Methods
15 -19. Syntax of Anonymous Methods служебное слово delegate; список параметров; блок операторов. Return type of delegate type ↓ delegate int Other. Del(int In. Param); // тип-делегат static void Main() { Other. Del del = delegate(int x) // экземпляр делегата { return x + 20 ; // Returns an int }; . . . }
15 -20. params Parameters params keyword used in delegate type declaration ↓ delegate void Some. Del( int X, params int[] Y); params keyword omitted in matching anonymous method ↓ Some. Del m. Del = delegate (int X, int[] Y) {. . . };
15 -21. Scope of Variables and Parameters
15 -22. Outer Variables
15 -23. Extension of Captured Variable’s Lifetime
15 -24. Lambda Expressions // Define a delegate type: delegate int My. Del( int X ); // Anonymous method: My. Del del = delegate(int x) { return x + 1; } ; // Lambda expression: My. Del le 1 = (int x) => { return x + 1; } ;
15 -25. Lambda Expressions delegate int My. Del( int X ); // Define a delegate type My. Del del = delegate(int x) { return x + 1; } ; // Anonymous method My. Del le 1 = (int x) => { return x + 1; } ; // Lambda expression My. Del le 2 = (x) => { return x + 1; } ; // Lambda expression My. Del le 3 = x => { return x + 1; } ; // Lambda expression My. Del le 4 = x => x + 1 ; // Lambda expression
15 -26. Синтаксис лямбда выражений