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 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--;
}
}
精彩评论