可能重复:
您何时在C#中使用委托?
代表们的目的
我看到很多关于代表使用的问题.我仍然不清楚你在哪里和为什么使用代理而不是直接调用方法.
我多次听过这个短语:"然后可以将委托对象传递给可以调用引用方法的代码,而不必在编译时知道将调用哪个方法."
我不明白这句话是怎么回事.
我写了以下例子.假设您有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;
}
Run Code Online (Sandbox Code Playgroud)
现在我宣布一个代表:
public delegate int Operations(int x, int y);
Run Code Online (Sandbox Code Playgroud)
现在我可以更进一步声明一个处理程序来使用这个委托(或你的委托直接)
致电代表:
MyClass f = new MyClass();
Operations p = new Operations(f.multiply);
p.Invoke(5, 5);
Run Code Online (Sandbox Code Playgroud)
或者使用处理程序调用
f.OperationsHandler = …Run Code Online (Sandbox Code Playgroud)