看板 C_Sharp 關於我們 聯絡資訊
有沒有加event的差異就在下面標紅色的部分 有加event的話 不能直接對定義此delegate做觸發 而只能+= -= 而沒加event的話 可以觸發delegate 也可以+= -= 所以使用event此keyword的目的好處是你可以隱藏觸發此event的邏輯 但又可外部去透過+= -=註冊event listener ============================ using System; class Test { public static void myTest() { Console.WriteLine("hello"); } public static void Main(string[] args) { TestA a = new TestA(); a.testEvent1 += myTest; a.testEvent2 += myTest; a.testEvent1(); //a.testEvent2(); this is invalid a.fireEvent2(); } } class TestA{ public delegate void test(); public test testEvent1; public event test testEvent2; public void fireEvent2() { testEvent2(); } } ※ 引述《QQ29 (我愛阿蓉)》之銘言: : 你好~ : 我看了書 消化一下 : event這個關鍵字 我把它刪掉 也一樣可以編譯成功 : event這關鍵字是不是只是一個強調的形容詞 : 並不是真的一定要加 : delegate給我的感覺樣是 C++的typedef : 我的感覺像是 用這個type去new一個instance : 而你也可以不用加上event這關鍵字 : 在語法上差異 : event 在 給他值時 需要用+= 給一個instance : 不加event 就可以直接用 +..... : 這邊不知道有沒有根深層的解釋 我只是片面的覺得是這樣 : 不知有沒有解讀錯誤@@ : 請指教 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.32.239.119 ※ 編輯: popcorny 來自: 114.32.239.119 (11/15 17:44)
Deadshot465:test這個型別在....? 11/15 18:10
Deadshot465:喔喔看到了@@ 11/15 18:10
Deadshot465:話說其實C# 4.0 In a Nutshell也有對Event做解釋 11/15 18:18
Deadshot465:原po可以去天瓏稍微翻一下 11/15 18:19