私は次のクラスを持っています:
public class FirstClass
{
public FirstClass()
{
list = new List<SomeType>();
}
public List<SomeType> list;
}
誰かがそのリストに要素を入れた後、これは別のメソッドを起動するようないくつかのアクションを実行することは可能ですか?
私は次のクラスを持っています:
public class FirstClass
{
public FirstClass()
{
list = new List<SomeType>();
}
public List<SomeType> list;
}
誰かがそのリストに要素を入れた後、これは別のメソッドを起動するようないくつかのアクションを実行することは可能ですか?
You should use a ObservableCollection<SomeType>
for this instead.
ObservableCollection<T>
provides the CollectionChanged
event which you can subscribe to - the CollectionChanged
event fires when an item is added, removed, changed, moved, or the entire list is refreshed.
Maybe you should be using ObservableCollection<T>
. It fires events when items are added or removed, or several other events.
Here is the doc: http://msdn.microsoft.com/en-us/library/ms668604.aspx
List
does not expose any events for that. You should consider using ObservableCollection
instead. It has CollectionChanged
event which occurs when an item is added, removed, changed, moved, or the entire list is refreshed.
you can do something like
private List<SomeType> _list;
public void AddToList(SomeType item)
{
_list.Add(item);
SomeOtherMethod();
}
public ReadOnlyCollection<SomeType> MyList
{
get { return _list.AsReadOnly(); }
}
but ObservableCollection would be best.
If you create your own implementation of IList you can call methods when an item is added to the list (or do anything else you want). Create a class that inherits from IList and have as a private member a list of type T. Implement each of the Interface methods using your private member and modify the Add(T item) call to whatever you need it to do
Code:
public class MyList<T> : IList<T>
{
private List<T> _myList = new List<T>();
public IEnumerator<T> GetEnumerator() { return _myList.GetEnumerator(); }
public void Clear() { _myList.Clear(); }
public bool Contains(T item) { return _myList.Contains(item); }
public void Add(T item)
{
_myList.Add(item);
// Call your methods here
}
// ...implement the rest of the IList<T> interface using _myList
}