C# 回调与 javascritp 回调 比较
C#:
using System; using System.Collections.Generic; using System.Text; namespace Delegate { //定义委托,它定义了可以代表的方法的类型 public delegate void welcomeDelegate(string name); class Program { private static void EnglishGreeting(string name) { Console.WriteLine("Hello, " + name); } private static void ChineseGreeting(string name) { Console.WriteLine("你好, " + name); } //注意此方法,它接受一个welcomeDelegate类型的方法作为参数 private static void GreetPeople(string name, welcomeDelegate WelcomeMethod) { WelcomeMethod(name); } static void Main(string[] args) { GreetPeople("Jimm", EnglishWelcome); GreetPeople("吉姆", ChineseWelcome); Console.ReadKey(); } } }
JS:
function ChinseWelcome(var name){ alert("你好"+name); } function EnglishWelcome(var name){ alert("hello"+name); } function WelcomePeople(var name,WelcomeMethod) { WelcomeMethod(name); } function test() { WelcomePeople("Jimm",ChinseWelcome); WelcomePeople("吉姆",EnglishWelcome); }
js 的回调与C#有异曲同工之妙,C#的代理功能更强大,增加了链式结构和轮播功能。