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.

  • ru.stackoverflow.com/q/479548/198316 I think that there is a fairly detailed answer to the question "why do we need delegates" - rdorn
  • @BadCats but you can think logically ...... you are without a delegate, you can just write MyClass.Method("djon"); if the Method not 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

1 answer 1

No, not right. See here:

 MyClass instance = new MyClass(); MyDelegate myDelegate = new MyDelegate(instance.Method); 

you first create an instance of the class, and then a delegate based on it. And here:

 string greetingg = MyClass.Method("djon"); 

you try to work with a function as with a static one when it is not. An error appears accordingly.

All this has nothing to do with delegates, only to objects and their members.