2017-09-30 43 views
2

我很努力地理解事件如何在C#上工作。 現在,我正在測試只有控制檯應用程序。我有時試過我在MSDN文檔中閱讀的內容,但未成功。C# - 簡單類的事件

這裏是我的代碼:

using System; 
using System.Collections.Generic; 

namespace Events 
{ 
    class MainClass 
    { 
     public static void Main(string[] args) 
     { 
      TodoList list = new TodoList(); 
      TodoItem fooItem = new TodoItem 
      { 
       Title = "FooItemTitle", 
       Description = "FooItemDescription", 
      }; 

      TodoItem barItem = new TodoItem 
      { 
       Title = "BarItemTitle", 
       Description = "BarItemDescription", 
      }; 

      // I want to trigger an event everytime a item is added on the 
      // TodoList. 
      // How can I do that? 
      list.AddItem(fooItem); 
      list.AddItem(barItem); 
     } 
    } 

    class TodoList 
    { 
     List<TodoItem> items; 
     public TodoList() 
     { 
      this.items = new List<TodoItem>(); 
     } 

     public void AddItem(TodoItem item) 
     { 
      this.items.Add(item); 
     } 
    } 

    class TodoItem 
    { 
     public String Description; 
     public String Title; 

     public override string ToString() 
     { 
      return string.Format("[TodoItem]: Title={0} | Description={1}", this.Title, this.Description); 
     } 
    } 
} 

我將如何配置到被觸發的事件,每次一個TodoItem是在TodoList加入?

+0

您可以使用'ObservableCollection'而不是'List',這會爲您創建事件 –

+0

謝謝埃裏克,我會看看。但我的意圖是瞭解事件流程。 – juniorgarcia

回答

1

您可以將事件添加到ToDoList

// note how we assigned a blank delegate to it 
// this is to avoid NullReferenceException when we fire event with no subscribers 

public event EventHandler<TodoItem> ItemAdded = (s, e) => { }; 

,並觸發其添加方法裏面:

ItemAdded(this, item); 

而且不要忘了從其他類預訂事件:

// as eventhandler you should use method that accepts exactly the same 
// number and type of parameters as in delegate EventHandler<TodoItem> 

list.ItemAdded += (eventhandler); 
+1

原來我的錯誤是忘記在我的AddItem方法中調用事件...謝謝。 – juniorgarcia