2017-09-30 47 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