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

问题描述 投票:1回答:1

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


    }
  }
}
c# class namespaces delegates public
1个回答
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;
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.