jeudi 19 novembre 2020

How to get all enumerable properties of a specific type from a class

Lets say I have a poco class that looks like this:

public MyClass
{
    public IAssimilator p1 {get; set;}
    public IAssimilator p2 {get; set;}
    public IAssimilator p3 {get; set;}
    public string n1 {get; set;}

    public List<IAssimilator> p4 {get; set;}
    public IEnumerable<IAssimilator> p5 {get; set;}
    public List<int> n2 {get; set;}
}

I have a method elsewhere that returns a List of all properties on MyClass that have type of IAssimilator. It looks like this:

private List<IAssimilator> DeltaTrackedMembers()
{
    var myInstance = new MyClass;
    ....
    ...
    return typeof(MyClass).GetProperties()
                .Where(p => p.PropertyType == typeof(IAssimilator))
                .Select(p => p.GetValue(myInstance) as IAssimilator)
                .ToList();
}

It will return a List<IAssimilator> that contains the values of p1 thru p3.

What I would like to add is something to also get IAssimilator values inside any enumerable property. In this case, it should return a List that contains the values in p4 and p5, but not n2. I don't really know where to start.





Aucun commentaire:

Enregistrer un commentaire