简体   繁体   中英

c# - how to access a list inside a generic object

I have a generic object containing a list with objects, which I like to access. By using

object sourceValue = new List<tab> {new tab()};
PropertyInfo[] sourcePropertyInfo = sourceValue.GetType().GetProperties();
//First field of PropertyInfo is the list, second is a Raw instance
object result = sourcePropertyInfo[0].GetValue(sourceValue, null);

Where the tab object looks like this:

public partial class tab
{
    public long TabId { get; set; }
    public string Title { get; set; }
}

Here I would like to access the list throught the result variable but it results in result = 0, which is an integer. Most likley it takes the count property from the list. How can I access the values in the objects in the list (of type tab)?

Note, I can not access or change the type of the object sourceValue.

You are getting properties of list type, not the type of elements.

foreach (object element in (sourceValue as IEnumerable ?? Enumerable.Empty<object>()))
{
   var type = element.GetType();
   var props = type.GetProperties();
   object result = props.First().GetValue(element, null);
}

Note: this can be optimized :)

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