前天接了個電話面試,被問到事件與委托的區別,雖然一直用但真要你說有什么區別一時半會還真說不上來。於是問google老師,得到如下答案:
1.事件的聲明只是在委托前面加一個event關鍵詞,雖然你可以定義一個public,但是有了event關鍵詞后編譯器始終會把這個委托聲明為private,然后添加1組add,remove方法。add對應+=,remove對應-=。這樣就導致事件只能用+=,-=來綁定方法或者取消綁定方法。而委托可以用=來賦值,當然委托也是可以用+=,-=來綁定方法的(面試我的那個哥們好像說不行)。
2.委托可以在外部被其他對象調用,而且可以有返回值(返回最后一個注冊方法的返回值)。而事件不可以在外部調用,只能在聲明事件的類內部被調用。我們可以使用這個特性來實現觀察者模式。大概就是這么多。下面是一段測試代碼。
namespace delegateEvent { public delegate string deleFun(string word); public class test { public event deleFun eventSay; public deleFun deleSay; public void doEventSay(string str) { if (eventSay!=null) eventSay(str); } } class Program { static void Main(string[] args) { test t = new test(); t.eventSay += t_say; t.deleSay += t_say; t.deleSay += t_say2; //t.eventSay("eventSay"); 錯誤 事件不能在外部直接調用 t.doEventSay("eventSay");//正確 事件只能在聲明的內部調用 string str = t.deleSay("deleSay");//正確 委托可以在外部被調用 當然在內部調用也毫無壓力 而且還能有返回值(返回最后一個注冊的方法的返回值) Console.WriteLine(str); Console.Read(); } static string t_say(string word) { Console.WriteLine(word); return "return "+word; } static string t_say2(string word) { Console.WriteLine(word); return "return " + word + " 2"; } } }