Allow any derivation of a generic class

  • Thread starter Thread starter Arthur Dent
  • Start date Start date
A

Arthur Dent

Hello all, ... quick question, I hope there's a quick answer....
(please forgive pseudo-code, don't have VB open right now)
Using VB2008 Express.

I have several classes which inherit
System.Collections.ObjectModel.KeyedCollection(Of TKey, TItem)
I want to add events for change notification (since this base class doesn't
supply any).

So I made an Enum (eg. ChangeTypes{Added, Changed, Removed, Cleared}).

I WANT to be able to make a single delegate to use for all the collections,
of the signature :
Public Delegate ChangeHandler As Sub (sender as SCO.KeyedCollection, action
as ChangeTypes)

But it wants me to strongly type the SCO.KeyedCollection argument. But I
want it to be able to just take ANY object which inherits
SCO.KeyedCollection, regardless of the types used to "define" the generic.

So for example I want both
SCO.KeyedCollection(Of String, Product) and
SCO.KeyedCollection(Of String, Discount)
to both be able to raise their events using the same delegate, as

RaiseEvent Changed As ChangeHandler(me, ChangeTypes.Added)
 
So for example I want both
SCO.KeyedCollection(Of String, Product) and
SCO.KeyedCollection(Of String, Discount)
to both be able to raise their events using the same delegate, as

RaiseEvent Changed As ChangeHandler(me, ChangeTypes.Added)


If you want the event handler to be aware of the type parameters, you
should make the delegate generic as well

Public Delegate Sub ChangeHandler(Of TKey, TItem)(sender as
SCO.KeyedCollection(Of TKey, TItem), action as ChangeTypes)

If that's not needed, you can pick a non-generic base type of
KeyedCollection, such as ICollection or IList, as the type for the
first delegate parameter.



Mattias
 
Generic delegates... wow, didn't realize you could do that, but now that you
point it out, its so obvious! ;)

Thanks for the pointer, works great.
CheerZ!
 
Back
Top