C# CSharp 回調函數

回調函數
回調函數就是把一個方法的傳給另一個方法去執行。在C#有不少回調函數,好比異步操做的時候。這裏先舉個例子:
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 回調函數本身寫的
 7 {
 8     public delegate string ProcessDelegate(int s1, int s2);
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string str1 = Process(2, 1, new ProcessDelegate(Add));
14             string str2 = Process(2, 1, new ProcessDelegate(Sub));
15 
16             Console.WriteLine(str1 + Environment.NewLine + str2);
17             Console.Read();
18         }
19         public static string Process(int i1, int i2, ProcessDelegate process)
20         {
21             return process(i1, i2);
22         }
23         public static string Add(int i1, int i2)
24         {
25             return (i1 + i2).ToString();
26         }
27         public static string Sub(int i1, int i2)
28         {
29             return (i1 - i2).ToString();
30         }
31     }
32 }
View Code

輸出結果:異步

3ide

1函數

回調函數,就是有一個參數是:一個委託的實例。對於該委託,有不少實際的函數實例化它。固然回調函數還有其餘參數可能用於在實例化的函數裏做爲參數使用。spa

相關文章
相關標籤/搜索