【C#】学习笔记(3) 关于Events使用的小Demo
关于Events事件的简单Demo.
目录结构:
Program.cs
1 using System; 2 namespace EventsDemo 3 { 4 class Program 5 { 6 static void Main(string[] args) 7 { 8 Book book = new Book(); 9 book.BookAdded += OnBookAdded; 10 book.AddBook("One"); 11 book.BookAdded -= OnBookAdded; 12 book.AddBook("Two"); 13 book.BookAdded += OnBookAdded; 14 book.AddBook("Three"); 15 book.BookAdded -= OnBookAdded; 16 book.AddBook("Four"); 17 } 18 static void OnBookAdded(object sender, EventArgs args) 19 { 20 System.Console.WriteLine("A book was added"); 21 } 22 } 23 }
Book.cs
1 using System; 2 namespace EventsDemo 3 { 4 public delegate void BookAddedDelegate(object sender, EventArgs args); 5 class Book 6 { 7 public void AddBook(string bookname) 8 { 9 if (BookAdded != null) 10 { 11 BookAdded(this, new EventArgs()); 12 System.Console.WriteLine($"BookName:{bookname}"); 13 } 14 } 15 public event BookAddedDelegate BookAdded; 16 } 17 }
输出:
这里有个小彩蛋~✨✨