可能的重复:
什么时候会在 C# 中使用委托? https://stackoverflow.com/questions/191153/when-would-you-use-delegates-in-c
代表的目的 https://stackoverflow.com/questions/687626/the-purpose-of-delegates
我看到很多关于使用代表的问题。我仍然不清楚在哪里以及为什么要使用委托而不是直接调用该方法。
我多次听到这句话:“然后可以将委托对象传递给可以调用引用方法的代码,而不必在编译时知道将调用哪个方法。”
我不明白这种说法是正确的。
我写了以下示例。假设您有 3 个具有相同参数的方法:
public int add(int x, int y)
{
int total;
return total = x + y;
}
public int multiply(int x, int y)
{
int total;
return total = x * y;
}
public int subtract(int x, int y)
{
int total;
return total = x - y;
}
现在我宣布一个代表:
public delegate int Operations(int x, int y);
现在我可以更进一步声明一个处理程序来使用此委托(或直接使用您的委托)
呼叫代表:
MyClass f = new MyClass();
Operations p = new Operations(f.multiply);
p.Invoke(5, 5);
或与处理程序调用
f.OperationsHandler = f.multiply;
//just displaying result to text as an example
textBoxDelegate.Text = f.OperationsHandler.Invoke(5, 5).ToString();
在这两种情况下,我看到我的“乘法”方法被指定。为什么人们使用“运行时更改功能”或上面的短语?
如果每次声明委托时,它都需要一个方法来指向,为什么要使用委托?如果它需要一个方法来指向,为什么不直接调用该方法呢?在我看来,我必须编写更多代码才能使用委托,而不仅仅是直接使用函数。
有人可以给我一个真实世界的情况吗?我完全困惑了。