Faced a problem I can not figure out how to solve, that is what is:

public class Info { public delegate string Method(int Value, string Name); public Method deleg; public Method deleg_1; public Info() { deleg = Quadratic_Equation; deleg_1 = Quadratic_Equation; deleg_1 += Cubic_Equation; } private string Quadratic_Equation(int a,string Name) { Console.WriteLine("1 метод"); return $"{Name} {a*a}"; } private string Cubic_Equation(int a,string Name) { Console.WriteLine("2 метод"); return $"{Name} {Math.Pow(a,3)}"; } } 

I call this:

  Info info = new Info(); Console.WriteLine(info.deleg(3,"Уравнение 1")); Console.WriteLine(info.deleg_1(3,"Уравнение 2")); Console.ReadKey(); 

How to correctly call delegate deleg_1 if I like Console.WriteLine(info.deleg_1(3,"Уравнение 2")); That only displays the data of the last method that attached to the delegate, how to do it correctly, that would output the data from the 1 and 2 methods attached to the delegate? (

    1 answer 1

    In order for Console.WriteLine work twice, it must be called twice.

    deleg_1 in this case is an array with two values. For Console.WriteLine to be called twice, you must enable it in the processing of this array. For example, pass as argument:

     public class Info { public delegate void Method(int Value, string Name, Action<string> processResult); public Method deleg; public Method deleg_1; public Info() { deleg = Quadratic_Equation; deleg_1 = Quadratic_Equation; deleg_1 += Cubic_Equation; } private void Quadratic_Equation(int a, string Name, Action<string> processResult) { Console.WriteLine("1 метод"); var result = $"{Name} {a * a}"; processResult(result); } private void Cubic_Equation(int a, string Name, Action<string> processResult) { Console.WriteLine("2 метод"); var result = $"{Name} {Math.Pow(a, 3)}"; processResult(result); } } class Program { static void Main(string[] args) { Info info = new Info(); info.deleg(3, "Уравнение 1", Console.WriteLine); info.deleg_1(3, "Уравнение 2", Console.WriteLine); Console.ReadKey(); } } 

    Result:

     1 метод Уравнение 1 9 1 метод Уравнение 2 9 2 метод Уравнение 2 27 
    • Thank!!!! But this kind of question: how to correctly declare the method, so that you can pass an expression to the lambda parameters? - Valera
    • one
      All the same, only the call can be changed info.deleg(3, "Уравнение 1", (v) => Console.WriteLine(v)); . - mals