I am new to this business, trying to learn and learn how to use delegates. Tell me how to fix it?
- oneDifferent return type - free_ze
2 answers
See it.
A delegate is just such a type that you can write not * numbers and objects, but functions * to variables of this type, and call them later. That's all you need to know to begin with.
To declare such a variable, the compiler must know what type of arguments this function will have, and what type of return value. He needs this so that he knows how to correctly call a function on this variable, and what type the result will be. When you declare a delegate, you provide this information and:
delegate int mydel(int x, int y); ^ \_____________________/ | | объявляется делегат | | а это показывает, какие функции использовать с этим делегатом только вместо имени функции название делегата In your code, the function returns a value, so the return value must also be in the delegate definition.
You can fix the code like this:
class Program { delegate int mydel(int x, int y); // поменяли возвращаемое значение на int static int sum(int x, int y) { return x + y; } static void Main(string[] args) { mydel g = sum; // здесь можно без new, просто присвоить. так проще, правда? int result = g(10, 5); Console.WriteLine("Sum = " + result); } } * ( Note to connoisseurs. ) Yes, this is a simplification. In fact, we have multicast delegate, so you can add and call them through Invoke / BeginInvoke . And yes, the delegate is an object. I simplify the picture for clarity.
You declared the delegate return type void, and pass the method with the return value int. Set the delegate's return value to int. There is also a suspicion that the method with the static modifier will not work. Do what I said, run and post.
- 2why not work with static functions? - Qutrix
- @Qutrix just suggested, I haven't used c # for a long time :) - Ep1demic
