2

私は次のクラスを持っています:

public class FirstClass 
{
   public FirstClass()
   {
       list = new List<SomeType>();
   }

   public List<SomeType> list;
}

誰かがそのリストに要素を入れた後、これは別のメソッドを起動するようないくつかのアクションを実行することは可能ですか?

4

5 に答える 5

5

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.

于 2012-04-09T16:10:49.880 に答える
4

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

于 2012-04-09T16:11:39.147 に答える
2

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.

于 2012-04-09T16:11:22.833 に答える
1

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.

于 2012-04-09T16:14:51.550 に答える
0

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
   }
于 2012-04-09T16:47:45.713 に答える