简体   繁体   中英

Reflection: how to get values from object as List<object>

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!

Try this:

public static void PrintListValues(IEnumerable<object> seq, string propName)
{
   foreach (var obj in seq)
   {
      var type = obj.GetType();
      var prop = type.GetProperty(propName);
      var value = prop.GetValue(obj);
      Console.WriteLine(value);
   }
}

Disclaimer: To play with reflection, the above code is fine. For a real world situation, there might be a few things to check as that code assumes the "happy path".

You likely just need

var values = anyList.Select(x => x.SomeProperty);

Console.WriteLine(string.Join(Environemnt.NewLine,values));

However if you really need to include a string property name

public IEnumerable<object> GetValues<T>(IEnumerable<T> source, string name)
{
   var prop = typeof(T).GetProperty(name) ?? throw new ArgumentNullException("typeof(T).GetProperty(propName)");
   return source.Select(x => prop.GetValue(x));
}

...

foreach (var value in GetValues(someList,"SomeProperty"))
   Console.WriteLine(value);

// or 

Console.WriteLine(string.Join(Environemnt.NewLine,GetValues(someList,"SomeProperty"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM