C# 回调函数理解和示例
时间: 2023-10-19 19:34:35 浏览: 181
回调函数是将一个方法作为参数传递给另一个方法的技术。在C#中,回调函数可以用来实现底层数据接收的回调、订单支付的回调等等。以下是两个示例来帮助理解回调函数在C#中的使用:
示例1:
```csharp
namespace CallBackFunction {
class Program {
static void Main(string[] args) {
Program prog = new Program();
SumClass sc = new SumClass();
int result = sc.SetCallBack(prog.GetSum);
Console.WriteLine(result.ToString());
}
private int GetSum(int a, int b) {
return (a + b);
}
}
class SumClass {
public delegate int Sum(int num1, int num2);
public Sum OnSum = null;
public void SetCallBack(Sum Parameter) {
this.OnSum = Parameter;
}
private void CallBackFunction(int num1, int num2) {
if (OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
private void CallBackFunction(int num1, int num2) {
if(OnSum != null) {
OnSum(num1, num2);
}
}
}
}
```
示例2:
```csharp
namespace CallBackFunction {
class Program {
static void Main(string[] args) {
Program prog = new Program();
SumClass sc = new SumClass();
int result = sc.SumAll(prog.GetSum);
Console.WriteLine(result.ToString());
}
private int GetSum(int a, int b) {
return (a + b);
}
}
class SumClass {
public delegate int Sum(int num1, int num2);
public int SumAll(Sum sum) {
//可以进行其他操作
return sum(1, 2);
}
}
}
```
在这两个示例中,我们可以看到回调函数的使用。在第一个示例中,通过将`GetSum`方法作为参数传递给`SetCallBack`方法来设置回调函数。在第二个示例中,通过将`GetSum`方法作为参数传递给`SumAll`方法来实现回调函数。这样,当回调函数被调用时,传递的方法将被执行并返回相应的结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [C# 回调函数个人理解和简单示例](https://blog.csdn.net/BYH371256/article/details/130658624)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文