Что произойдет, если вы поместите функции из двух классов в один делегат? - PullRequest
0 голосов
/ 08 сентября 2018

Я готовлюсь к экзамену, и мне приходится изучать различные коды. Один из них касается делегатов в C # - я не вижу, что он делает, поскольку я не знаю, можно ли поместить функции из двух разных классов в один делегат.

Вот код:

namespace konzolnaApplikacijaDelegateVoidMain {

public delegate int MyDelegate(int x);

class Program
{

    public int number;

    public Program (int x)
    {
        number = x;
    }

    public int Add(int x)
    {
        return x + 10;
    }

    public int Substract(int x)
    {
        return x - 10;
    }

    public int Multiply(int x)
    {
        return x * 2;
    }

    static void Main(string[] args)
    {
        MyDelegate delegate;
        Program first = new Program(20);
        Program second = new Program(50);

        delegate = first.Add;
        delegate += second.Add;
        delegate -= first.Substract;
        delegate += second.Multiply;
        delegate += first.Add;

        delegate(first.number);
        delegate(second.number);

        Console.Write("{0}", first.number + second.number);


    }
  }
}

1 Ответ

0 голосов
/ 08 сентября 2018

Делегаты довольно просты. Рассмотрим следующую реализацию делегата.

namespace DelegateExamples
{
    class Program
    {
        //Declare a integer delegate to handle the functions in class A and B
        public delegate int MathOps(int a, int b);
        static void Main(string[] args)
        {
            MathOps multiply = ClassA.Multiply;
            MathOps add = ClassB.Add;
            int resultA = multiply(30, 30);
            int resultB = add(1000, 500);
            Console.WriteLine("Results: " + resultA + " " + resultB);
            Console.ReadKey();
        }
    }
    public class ClassA
    {
        public static int Multiply(int a, int b)
        {
            return a * b;
        }
    }
    public class ClassB
    {
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
}
...