I've been working with generics over the last few days and I encountered an issue by trying to pass generic types as parameters in events/delegates.
A very friendly member of stack could bring some light into one question about generics I posted last Friday. However, I'd like to bring this up again, because I still don't understand how I am supposed to make it work correctly.
In the following code you can see that I have a class "Catalog", which can raise an event, which contains a generic parameter.
The class "MainWindow" subscribes to this event and should work with the generic parameter.
This doesn't work, because the event must specify the generic type of the delegate.
public class Catalog {
#region EVENTS
public delegate void GenericListItemCountChangedEvent<T>(object sender, GenericListItemCountChangedEventArgs<T> e) where T : BaseItem;
//This is the point where it does not work, because I specify BaseItem as the type
public event GenericListItemCountChangedEvent<BaseItem> GenericListItemCountChanged;
private void RaiseGenericListItemCountChangedEvent<T>(List<T> List) where T : BaseItem {
if (GenericListItemCountChanged != null) {
GenericListItemCountChanged(this, new GenericListItemCountChangedEventArgs<T>(List));
}
}
public class GenericListItemCountChangedEventArgs<T> : EventArgs where T : BaseItem {
private List<T> _changedList_propStore;
public List<T> ChangedList {
get {
return _changedList_propStore;
}
}
public GenericListItemCountChangedEventArgs(List<T> ChangedList){
_changedList_propStore = ChangedList;
}
}
#endregion EVENTS
}
public partial class MainWindow : Window{
public MainWindow(){
_catalog.GenericListItemCountChanged += (sender, e) => GenericListItemCountChanged(sender, e);
}
private void GenericListItemCountChanged<T>(object sender, Catalog.GenericListItemCountChangedEventArgs<T> e) where T : BaseItem {
//Use Generic EventArgs
}
}
Is there a way to receive the generic parameter in the class "MainWindow"? Or do I need to implement some work-around?