I have a class that manages collections of objects e.g. List<Car>
and List<Bike>
which are atribute.
I'd like to find a way to get a reference to each of those collections in a lookup so I can implement methods such as Add<Car>(myCar)
or Add(myCar)
(with reflection) and it will add it to the right collection.
I tried the following,
public class ListManager
{
private Dictionary<Type, Func<IEnumerable<object>>> _lookup
= new Dictionary<Type, Func<IEnumerable<object>>>();
public ListManager()
{
this._lookup.Add(typeof(Car), () => { return this.Cars.Cast<object>().ToList(); });
this._lookup.Add(typeof(Bike), () => { return this.Bikes.Cast<object>().ToList(); });
}
public List<Car> Cars { get; set; }
public List<Bike> Bikes { get; set; }
}
but .ToList()
creates a new list and not a reference, so _lookup[typeof(Car)]().Add(myCar)
is only added to the dictionary list.