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
加入?
您可以使用'ObservableCollection'而不是'List',這會爲您創建事件 –
謝謝埃裏克,我會看看。但我的意圖是瞭解事件流程。 – juniorgarcia