开发者

Associate List<T>.Remove to an event in C#?

开发者 https://www.devze.com 2022-12-22 20:54 出处:网络
I have a Products:List<Product> class. I\'d like to make it so that every time that I remove an item from that list, my program decreases a counter.

I have a Products:List<Product> class. I'd like to make it so that every time that I remove an item from that list, my program decreases a counter.

Is there a way to do it without overriding the Remove method or decreasing it manually? And if there is none, anybody knows where I can find the code for the Remove method?

Thanks!

I thought about associating the Remove method to an event, but I don't know how to do it without overriding it or creating another method with the Remove method and the event inside it. Excuse me for my ignorance, but I'm just getting开发者_运维问答 into OOP programming.


You could use an ObservableCollection<Product>. It is in System.Collections.ObjectModel It will fire an event when the collection changed. The arguments of the event will tell you if it is an removal, an addition etc.


List do not provide any event. So you might have to drive from this class and shadow the remove method to fire an event

public new bool Remove()
{
   bool removed = base.Remove();
   if(removed)
   {
       OnRemoved();
   }
   return removed;
}


This would be a quick and dirty way to meet your requirement, but I think there might be more to what you're trying to achieve:

class Strings : List<String> {
    private Int32 _numberOfRemovals = 0;

    public Int32 NumberOfRemovals {
        get { return _numberOfRemovals; }
    }

    public new void Remove(String s) {
        base.Remove(s);
        _numberOfRemovals--;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号