jeudi 19 janvier 2023

How to access the methods of a generic ObservableCollection?

public class Car
{
    public ObservableCollection<int> ints = new ObservableCollection<int> { 12, 3, 4, 1, 2 };
    public ObservableCollection<double> doubles = new ObservableCollection<double> {  };
    public ObservableCollection<string> strings = new ObservableCollection<string> { 12, 3, 4, 1, 2 };
    public ObservableCollection<Color> colors = new ObservableCollection<Color> { ColorA, ColorB, ColorC };

}

Let's say I have a class call Car, inside the class, I have 4 lists.

In another class, I would like use Reflection to call a Linq method to find if these four lists contain anything.

    public void FindProperties()
    {
        foreach (var prop in typeof(Car).GetProperties())
        {
            if (prop.PropertyType == typeof(ObservableCollection<T>))
            {
                var list = (ObservableCollection<T>)prop.GetValue(Car);
                if (list.Any()) 
                  {//Do something}
            }
        }
     }

Since ObservableCollection< T > isn't a thing, the code is not working, but hopefully it explains what I attempt to do. Inside the Car class I actually have 40+ of these lists and I really don't want to do a switch and case cast to do that. It doesn't seem very clean and smart to do that either.

I don't need to know what is T, I just need to know if the list contains anything and maybe use the CollectionChanged event as well. What is the best way to do it apart from casting each field?





Aucun commentaire:

Enregistrer un commentaire