B
B
BadCats2016-04-15 13:30:17
C++ / C#
BadCats, 2016-04-15 13:30:17

Delegates and their instances?

hello everyone, just started learning delegates. and so far I understood the following:
in order to create a delegate, we first create a delegate class (yes, yes, I know that this is not quite the correct name)

public delegate void MyDelegate();  // Создаем класс делегата. (1)

the delegate class describes the signature of the method that we communicate (from the word make common) with this delegate.
// Создаем статический метод, который планируем сообщить с делегатом.
        public static void Method()
        {
            Console.WriteLine("Строку вывел метод сообщенный с делегатом.");
        }

then, we create an instance of the delegate, the constructor of which takes the method we need for the message:
MyDelegate myDelegate = new MyDelegate(MyClass.Method); // Создаем экземпляр делегата. (2)

so how i understood if the signature of another method
// Создаем статический метод, который планируем сообщить с делегатом.
        public static void MyMethod()
        {
            Console.WriteLine("Строку вывел метод сообщенный с делегатом.");
        }

- matches the signature of the delegate class, then we only need to create one more instance of the delegate
MyDelegate myDelegate = new MyDelegate(MyClass.MyMethod); // Создаем экземпляр делегата. (2)

and just pass another method with the same signature as a constructor parameter (except for the name, of course
) method (the type of the returned and accepted values) and then, respectively, an instance of this delegate class.
That is, as I understand it, if the signature of two or three methods in the program is the same (except for the name), then we can simply "clip" delegate instances, each of which will be communicated with its own of these several methods. And if three methods have the same signature, and the fourth one has a different signature, then for this you will have to create a new delegate class.
Did I understand everything correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kovalsky, 2016-04-15
@BadCats

Yes, you almost got it right. For methods with the same signature, one delegate is enough, for a method with a different signature, another delegate is required.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question