hello everyone, just started to learn delegates. There is such an example:
// Класс, метод которого будет сообщен с делегатом. class MyClass { // Создаем метод, который планируем сообщить с делегатом. public string Method(string name) { return "Hello " + name; } } // На 21-й строке создаем класс-делегата с именем MyDelegate, // метод, который будет сообщен с экземпляром данного класса-делегата, // будет принимать один строковой аргумент и возвращать строковое значение. public delegate string MyDelegate(string name); // Создаем класс делегата. (1) class Program { static void Main() { MyClass instance = new MyClass(); MyDelegate myDelegate = new MyDelegate(instance.Method); // Создаем экземпляр делегата и сообщаем с ним метод. (2) string greeting = myDelegate.Invoke("djon"); // Вызываем метод сообщенный с делегатом. (3) Console.WriteLine(greeting); greeting = myDelegate("Grady Booch"); // Другой способ вызова метода сообщенного с делегатом. (3') Console.WriteLine(greeting); // Delay. Console.ReadKey(); } } For the sake of interest, replaced the line:
string greeting = myDelegate("djon"); // Вызываем метод сообщенный с делегатом. (3) on
string greetingg = MyClass.Method("djon"); and got the following error from visual studio 2012:
Error 1 A non-static field, method, or property "Delegates.MyClass.Method (string)" requires an object reference.
After all, the delegate is the object that contains the pointers to methods.
Ie this example with an error made by me for the sake of experiment, and there is a clear or you can say a vital example why it is necessary to use delegates?
If so, then good, if not then give your life examples of the use of delegates.
MyClass.Method("djon");if theMethodnot static? Not! You must first create an instance from the class with which it is associated. So why do you want these laws to be broken down here? - Alexey Shimansky