В зависимости от того как часто будет вызываться этот метод, результаты его работы можно кешировать
public class CollectionsStorage
{
private readonly Dictionary<Type , Object> _objects = new Dictionary<Type , Object>();
public ObservableCollection<Car> Cars { get; set; } = new();
public ObservableCollection<Animal> Animals { get; set; } = new();
// Тип "T" это Animal или Car.
public IEnumerable<T>? GetObjects<T>()
{
if (_objects.TryGetValue(typeof(T) , out Object obj))
{
return (IEnumerable<T>)obj;
}
PropertyInfo[] properties = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)
.Where(prop => prop.PropertyType.IsAssignableTo(typeof(IEnumerable<T>)))
.ToArray();
if (properties.Length == 0)
{
throw new ArgumentException("Type T not found");
}
if (properties.Length > 1)
{
throw new ArgumentException("Type T more than one");
}
object result = properties.First().GetValue(this)!;
_objects[typeof(T)] = result;
return (IEnumerable<T>)result;
}
}