jeudi 1 novembre 2018

C# reflection get fields that implement a specific generic interface and access a property

I have this interface

public interface IGenericInterface<T>
{
    List<foo> FooList {get ; set;}
}

And a class something like this

public class SomeClass
{

    private readonly IGenericInterface<Type1> object1;
    private readonly IGenericInterface<Type2> object2;
    // code...

    public DoSomething()
    {
        GetLists(this) //the idea is to extract to static class
    }

    private List<foo> GetLists(object aClass)
    {
        //The idea here is with reflection get all the fields but I only want to get the ones that implements IGenericInterface
         var fields = aClass.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
         //each field that implement generic interface, get the items from fooList.
    }
}

I don't know how to implement the GetLists method to return a consolidated list. I mean how to iterate the fields, get the one that implements IGenericInterface and access the FooList which is public in the implementations.





Aucun commentaire:

Enregistrer un commentaire