你好,我有以下代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myConsole
{
public delegate int showDelegate();
public class addmultipleClass
{
public int addNumbers(int a, int b)
{
return (a + b);
}
public int multiplyNumbers(int a, int b)
{
return (a * b);
}
}
class Delegate
{
static void Main(string[] args)
{
addmultipleClass myObj = new addmultipleClass();
showDelegate add = new showDelegate(myObj.addNumbers);
}
}
}
它显示这样的错误 'addNumbers' 的重载不匹配委托(delegate) 'myConsole.showDelegate'
为什么会显示这个错误。我的代码有什么问题。引用 addNumbers() 方法的方法不正确吗?
我为什么要在这里使用委托(delegate)。我可以通过使用类对象来实现这一点。作为 myObj.addNumbers(10,20); 那么委托(delegate)的必要性是什么? 请帮我。 谢谢大家。
请您参考如下方法:
修改 showDelegate 以匹配 addNumbers 的参数:
public delegate int showDelegate(int a, int b);
除返回类型外,委托(delegate)还必须匹配参数的数量和类型。
您问题的第二部分本质上是在问:“为什么要委托(delegate)?”。对于这个答案,我建议您首先查看其他 Stack Overflow 帖子以获得更详细和准确的答案:
Delegates, Why? when & why to use delegates? The purpose of delegates
