如果将两个类中的函数放在一个委托中会发生什么?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果将两个类中的函数放在一个委托中会发生什么?相关的知识,希望对你有一定的参考价值。

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


    }
  }
}
答案

代表们很简单。考虑以下代理实现。

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

以上是关于如果将两个类中的函数放在一个委托中会发生什么?的主要内容,如果未能解决你的问题,请参考以下文章

C#中的委托是啥?事件是否一种委托?

[C++11]委托构造函数

多个 REST API 方法可以共享同一个控制器类吗?

委托构造函数详解,小白也可以看懂

NSObject 类中的委托

模板类中的非模板函数[关闭]