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

輸出結果:

3

1

回調函數,就是有一個參數是:一個委托的實例。對於該委托,有很多實際的函數實例化它。當然回調函數還有其他參數可能用於在實例化的函數里作為參數使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM