如果将来自两个类的函数放在一个委托中会怎样?

时间:2018-09-08 13:39:21

标签: c# class namespaces delegates public

我正在准备考试,我必须检查各种代码。一种是关于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 :(得分:1)

代表很简单。考虑委托的以下实现。

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;
        }
    }
}