【问题标题】:What happens if you put functions from two classes in one delegate?如果将两个类的函数放在一个委托中会发生什么?
【发布时间】:2019-02-13 14:16:41
【问题描述】:

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


    }
  }
}

【问题讨论】:

  • 我不希望这段代码能够编译,因为“delegate”是一个 C# 关键字,但在您的示例中被用作变量。话虽如此,我认为下面链接的问题的答案会对您有所帮助。 stackoverflow.com/questions/28391414/…
  • 也检查这个问题。它涵盖了 += 和 -= 运算符如何处理委托。 stackoverflow.com/questions/17935299/…
  • 将非void 委托组合成一个多播委托是灾难的根源。对于应该从它们返回的内容,有各种“正确”的答案,并且您不能保证您想要的任何答案都是 .NET 开箱即用的。 (请注意,在这种情况下,您也忽略了返回值,所以也是如此)
  • 注意,即使他们上面的documentation 也没有提到返回值
  • 我的错误,考虑到它说的是“dg”而不是“delegate”。我想知道这段代码是否只会返回订阅的最后一个方法的值?

标签: c# class namespaces delegates public


【解决方案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;
        }
    }
}

【讨论】:

  • 我不清楚大部分问题,但似乎很清楚的一件事是他们正在询问 combining 代表,即创建多播代表。因此,我看不出这个答案在解决什么问题。而且您还没有真正提供任何解释来说明为什么这应该回答他们的问题。
  • 实际上,我想知道给定代码的返回值是什么...在我找到的一些材料中,它说它只会返回最后添加的方法的值(订阅)给代表。这是真的吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-21
相关资源
最近更新 更多