jeudi 25 mai 2017

Reflection : How to get the result (and do foreach on it) from method invoked using Reflection?

I would like to invoke some methods from different repository and having the same type "List<>" as result but I don't know how to cast the result without hard code and also how to use "foreach" on this result, here the example below :

class Person
{
    public string Name { get; set; }
}

class Animal
{
    public string Name { get; set; }
}

class PersonRepository
{
    public List<Person> GetPersons()
    {
          List<Person> list = new List<Person>();

          //Some processing...

          return list;
    }
}

class AnimalRepository
{
    public List<Animal> GetAnimals()
    {
        List<Animal> list = new List<Animal>();

        //Some processing...

         return list;
    }
}

public class ReflectionClass
{
    public List<T> GetResultFromMethodInvoked<T>(string entityName, string repositoryName, string methodName)
    {
        List<T> lists = new List<T>();
        Type entity_type = Type.GetType("Entities." + entityName + " ,Entities");
        Type repository = Type.GetType("Crud." + repositoryName + ", Crud");
        MethodInfo method = repository.GetType().GetMethod(methodName);


        var r= method.Invoke(repository, parameters);


        Convert.ChangeType(r, typeof(List<>).MakeGenericType(new Type[] { entity_type }));

        lists = (List<T>)r;

        return lists;
    }
}

class Program
{
    static void Main(string[] args)
    {
        ReflectionClass reflection = new ReflectionClass();
        /* Should have List<Person> as RESULT */
        reflection.GetResultFromMethodInvoked("Person", "PersonRepository", "GetPersons");

        /* Should have List<Animal> as RESULT */
        reflection.GetResultFromMethodInvoked("Animal", "AnimalRepository", "GetAnimals");
    }
}





Aucun commentaire:

Enregistrer un commentaire