jeudi 20 août 2020

Reflection: how to get values from object as List

Using reflection, I need a function that accepts a list of generic objects and print its values

List<Gender> genders = new List<Gender> {
    new Gender {
        Id: 1,
        Name: "Male"
    },
    new Gender {
        Id: 2,
        Name: "Female"
    }
}

PrintListValues(genders, "Name"); // prints Male, Female

PrintListValues has to accept a list as object. And the list can contain any type of object. As long as the generic object have the property passed in, it should print the value of each item in list.

public static void PrintValues(object listObject) 
{
     // code here
} 

Unfortunately that's the way the project requirement is.

Been scratching my head over this one and can't figure it out. Reflection is too difficult for me. If anyone can give me hint that would be great!





Aucun commentaire:

Enregistrer un commentaire