Delving into Troelsen’s book about delegates, he noticed such a funny thing that delegates can be used in the manner of events and have my own question in my delegate registrar method that looks like this
public class Car { // 1. Определить тип делегата. public delegate void CarEngineHandler(string msgForCaller); // 2. Определить переменную-член типа этого делегата. private CarEngineHandler listOfHandlers; // 3. Добавить регистрационную функцию для вызывающего кода. public void RegisterWithCarEngine(CarEngineHandler methodToCall) { listOfHandlers = methodToCall; } } Here, the RegisterWithCarEngine method takes the delegate object as a parameter and then further defines the method for invoking the delegate.
// 4. Реализовать метод Accelerate() для обращения // к списку вызовов делегата при нужных условиях. public void Accelerate(int delta) { // Если этот автомобиль сломан, отправить сообщение об этом. if (carIsDead) { if (listOfHandlers != null) listOfHandlers("Sorry, this car is dead..."); } else { CurrentSpeed += delta; // Автомобиль почти сломан? if (10 == (MaxSpeed - CurrentSpeed) && listOfHandlers != null) { listOfHandlers("Careful buddy! Gonna blow!"); } if (CurrentSpeed >= MaxSpeed) carIsDead = true; else Console.WriteLine("CurrentSpeed= {0}", CurrentSpeed); } } And after all this, in the main, we call the method for registering the delegate, but this was not done in a usual way for me in the usual way as it passes an anonymous delegate object (by calling the constructor and passing it the method name), which is then assigned to the field that is declared in the class for storing information about what method will be called when an event occurs (here, as if by delegates, this is done not to be confused with events) and this is the actual code that caused my question and I would like to clarify whether an anonymous object is transmitted correctly t delegate
class Program { static void Main(string[] args) { Console.WriteLine("***** Delegates as event enablers *****\n"); // Сначала создать объект Car. Car cl = new Car("SlugBug", 100, 10); // Теперь сообщить ему, какой метод вызывать, // когда он захочет отправить сообщение. cl.RegisterWithCarEngine(new Car.CarEngineHandler(OnCarEngineEvent)); // Ускорить (это инициирует события). Console.WriteLine("***** Speeding up *****"); for (int i = 0; i < 6; i++) cl.Accelerate(20); Console.ReadLine(); } // Это цель для входящих сообщений. public static void OnCarEngineEvent(string msg) { Console.WriteLine("\n***** Message From Car Object *****"); Console.WriteLine("=> {0}", msg); Consоle.WriteLine("* * *\n"); } } That directly absolutely specifically that line with a call of a method RegisterWithCarEngine and its argument which actually is a call of a method new that exactly here will occur is interested. Type creating a delegate object with no name and then we will pass it to the field that is in each object of the Car class and thus write down what method to call (I would be more understandable if we say passed the delegate variable, but here it’s done and I want to clarify whether got it)
CarEngineHandleris just the delegate signature, not the delegate itself. That is, you describe in it what arguments and what return value.new Car.CarEngineHandler(OnCarEngineEvent))is already directly creating a delegate that will call the OnCarEngineEvent method every time the delegate itself is called. At the time of calling theRegisterWithCarEnginemethod, as in the call of any method, everything that is in the arguments is first calculated, and then it is sent to the method. In this case, the delegate is first created, and the already-prepared delegate is sent further as an argument. - John