c# - ISet that notifies on add and remove? -
c# - ISet<T> that notifies on add and remove? -
i'd iset<t>
2 additional events itemadded
, itemremoved
.
one alternative considered deriving myhashset<t>
hashset<t>
since add
, remove
not virtual, require utilize of new
. maybe valid utilize of keyword?
another alternative thought implement iset<t>
, delegate private instance of hashset<t>
. feels bulky solution.
is there pattern or framework class gets me same result doesn't require less elegant/ideal coding?
your own reply demonstrates how can wrap hashset<t>
, srikanth's reply demonstrates how can derive hashset<t>
. however, when derive hashset<t>
have create sure new class correctly implements add
, remove
methods of icollection<t>
interface. have modified srikanth's reply create iset<t>
implementation notifications derives hashset<t>
using explicit interface implementation of relevant methods of icollection<t>
:
public class notifyinghashset<t> : hashset<t>, icollection<t> { new public void add(t item) { ((icollection<t>) this).add(item); } new public boolean remove(t item) { homecoming ((icollection<t>) this).remove(item); } void icollection<t>.add(t item) { var added = base.add(item); if (added) onitemadded(new notifyhashseteventargs<t>(item)); } boolean icollection<t>.remove(t item) { var removed = base.remove(item); if (removed) onitemremoved(new notifyhashseteventargs<t>(item)); homecoming removed; } public event eventhandler<notifyhashseteventargs<t>> itemadded; public event eventhandler<notifyhashseteventargs<t>> itemremoved; protected virtual void onitemremoved(notifyhashseteventargs<t> e) { var handler = itemremoved; if (handler != null) itemremoved(this, e); } protected virtual void onitemadded(notifyhashseteventargs<t> e) { var handler = itemadded; if (handler != null) itemadded(this, e); } } public class notifyhashseteventargs<t> : eventargs { public notifyhashseteventargs(t item) { item = item; } public t item { get; private set; } }
this class behaves same way class firing events when element added or removed set. e.g., adding same element twice in succession fire 1 event.
c#
Comments
Post a Comment