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
에 추가 트리거하도록 구성 할 것입니다 :
여기 내 코드?
ItemAdded(this, item);
또한
가 다른 클래스에서 이벤트에 가입하는 것을 잊지 마세요 :
// 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) => { };
을 그리고 Add 메서드의 내부를 트리거 :
'List' 대신에'ObservableCollection'을 사용할 수 있습니다. 그러면 당신을 위해 이벤트가 생성 될 것입니다. –
감사합니다. 에릭, 한번 살펴 보겠습니다. 하지만 내 의도는 이벤트 흐름을 이해하는 것입니다. – juniorgarcia