samedi 13 octobre 2018

Generic Add method in class composed of multiple lists

I have a class composed of multiple lists and I have generic methods to allow me to do CRUD (and other) operations over those lists.

I'm basically trying to do a variation of DbContext.Set<T> with List.

This is my situation:

public class A
{
    private IList<B> Bs;
    private IList<C> Cs;

    public A()
    {
        Administrators = new List<B>();
        Developers = new List<C>();
    }

    public void Add<T>(T entity)
    {
        var propertyIWant = this.GetType().GetProperties().Where(p => p.GetType() == typeof(IList<T>));
        var propertyAsList = propertyIWant as List<T>;
        propertyAsList.Add(entity);
    }

    public void Delete<T>(T entity)
    {
       //Same idea 
    }

    //Other methods
}

The problem is that my code gives me a list of the desired type, but no the actual list (i.e. the property). So any modifications to that list don't modify the property.

I'd like to be able to do something akin to A.List<T> to get the list of that type (like DbContext can do with DbContext.Set<T>).





Aucun commentaire:

Enregistrer un commentaire