.NET reflection - getting the first item out of a reflected collection without casting to specific collection
I've got a Customer object with a Collection of CustomerContacts
IEnumerable<CustomerContact> Contacts { get; set; }
In some other code I'm using Reflection and have the PropertyInfo of Contacts property
var contacts = propertyInfo.GetValue(customerObject, null);
I know contacts has at least one object in it, but how do I get it out? I don't want to Cast it to IEnumerable<CustomerContact>
because I want to keep my reflection method dynamic. I thought about calling FirstOrDefault() by reflection开发者_C百科 - but can't do that easily because its an extension method.
Does anyone have any ideas?
If you really want to avoid mentioning CustomerContact
in your code, you could do this:
IEnumerable items = (IEnumerable)propertyInfo.GetValue(customerObject, null);
object first = items.Cast<object>().FirstOrDefault();
精彩评论