0

I don't know whether I'm using the correct terms for my problems, so hopefully it's understandable what I need help for.

Currently I have:

public class MyCollection<T, U> : ObservableCollection<T>, IParented<U> {..}

public class MyInitClass()
{
    var bindingFlags = BindingFlags.Instance | BindingFlags.Public |     BindingFlags.NonPublic;
    var fieldValues = obj.GetType().GetFields(bindingFlags).Where(x => x.FieldType.Name.StartsWith("MyCollection"));

    foreach (FieldInfo fieldInfo in fieldValues)
    {
        var list = fieldInfo.GetValue(obj);

        if (list is MyCollection<MyClassA> classA)
            classA.CollectionChanged += Abstract_CollectionChanged;
        else if (list is MyCollection<MyClassB> classB)
            classB.CollectionChanged += CollectionChanged;
        else if (list is MyCollection<MyClassC> classC)
            classC.CollectionChanged += CollectionChanged;
        ...
    }
}

This works fine, the problem is that I have dozens of classes and classes are added and removed constantly, thus this if else is annoying and hopefully there is a better way. I only want to subscribe the CollectionChanged event, the actual values doesn't bother me here.

dynamic list = fieldInfo.GetValue(obj);
list.CollectionChanged += Abstract_CollectionChanged;

does not work, as events cannot be subscribed when dynamic is used.

So is there a way to subscribe to the event without performing this endless if-else?

Thanks in advance!

Hagi
  • 140
  • 1
  • 8
  • and how `CollectionChanged` is defined? you may add common interface just cast to it and subscribe for event (of course if `CollectionChanged` is not specialized with generic parameter) – Selvin Aug 13 '21 at 12:37
  • Why not [using reflection to subscribe](https://stackoverflow.com/q/4104789/1997232)? I guess all `MyCollectionXXX` will have similar delegate for `CollectionChange` event? – Sinatr Aug 13 '21 at 12:54
  • @Selvin MyCollection is derived from `ObservableCollection`, which provides the event `CollectionChanged` – Hagi Aug 13 '21 at 13:05

1 Answers1

1

If your generic MyCollection<T> implements the non-generic INotifyCollectionChanged interface (this is the case if it is derived from ObservableCollection<T>), then the whole foreach can be simplified like this:

foreach (FieldInfo fieldInfo in fieldValues)
{
    var list = fieldInfo.GetValue(obj);

    if (list is INotifyCollectionChanged notifyCollectionChanged)
        notifyCollectionChanged.CollectionChanged += CollectionChanged;
    ...
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65