vendredi 13 août 2021

Cast generic list gathered by relection for subscribing event

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!





Aucun commentaire:

Enregistrer un commentaire