C # delegate only writes out the last method

I have this code:

public void myMethod()
{
    int a = 10;
    int b = 20;
    Func<int, int, int> multiplyDelegate;
    multiplyDelegate = Multiply;
    multiplyDelegate += Multiply2;

    Console.WriteLine(multiplyDelegate(a,b));
}

public int Multiply(int x, int y)
{
    return x * y;
}
public int Multiply2(int x, int y)
{
    return x * y + 10;
}

By running myMethod, I expect the console to show the returned data from both the Multiply and Multiply2 methods, but only the return from the Multiply2 method is shown. Did I do something wrong, or did I misunderstand the concept of delegates? From what I learned, the delegate is an array of method references.

+4
source share
4 answers

You are right, the delegate can store methods and call several methods at once. It will return the last, unless you explicitly call them.

Using your code, here is an example of an explicite Invoke for your entire collection of methods.

var results = multiplyDelegate.GetInvocationList().Select(x => (int)x.DynamicInvoke(10, 20));
foreach (var result in results)
    Console.WriteLine(result);

EDIT:

Func, Action. , Action

foreach (Delegate action in multiplyDelegate.GetInvocationList())
{
    action.DynamicInvoke(10, 20);
    // Do Something
}

Func.

+4

( #):

/ , .

+12

, Multiple2 , .

.

:

public void myMethod()
        {
            int a = 10;
            int b = 20;
            Action<int, int> multiplyDelegate;
            multiplyDelegate = Multiply;
            multiplyDelegate += Multiply2;
            multiplyDelegate(10, 20);

            Console.Read(); 
        }

        public void Multiply(int x, int y)
        {
            Console.WriteLine(x * 2);
        }
        public void Multiply2(int x, int y)
        {
            Console.WriteLine(x * y + 10);
        }
+1

, , , . .

Although only the last return value is used, both methods actually execute. We can prove this by printing some things before we go back:

public int Multiply(int x, int y)
{
    Console.WriteLine("Hello1");
    return x * y;
}
public int Multiply2(int x, int y)
{
    Console.WriteLine("Hello2");
    return x * y + 10;
}

Both Hello1 and Hello2 will be printed.

+1
source

Source: https://habr.com/ru/post/1675609/


All Articles