简体   繁体   中英

Getting properties using reflection

I'm using reflection for getting some properties, and I'm having problems getting one when the GetValue(item,null) returns an object. I did:

foreach (var item in items)
{
   item.GetType().GetProperty("Site").GetValue(item,null)
}

Doing that, I got an object System.Data.Entity.DynamicProxies.Site . Debugging it, I can see all properties of that object, but I can't get it. For example, one property is: siteName , how can I get the value of that?

DynamicProxies generated by Entity Framework are descendants of your POCO classes. That is, you actually can access all properties if you upcast the result to POCO:

foreach (var item in items)
{
   YourNamespace.Site site = (YourNamespace.Site)item.GetType().GetProperty("Site").GetValue(item,null);
   Console.WriteLine(site.SiteName);
}

If you need to use reflection for some reason, this is also possible:

foreach (var item in items)
{
    PropertyInfo piSite = item.GetType().GetProperty("Site");
    object site = piSite.GetValue(item,null);
    PropertyInfo piSiteName = site.GetType().GetProperty("SiteName");
    object siteName = piSiteName.GetValue(site, null);
    Console.WriteLine(siteName);
}

Reflection is slow, so I would use TypeDescriptor if I do not know the Type in compile time:

PropertyDescriptor siteProperty = null;
PropertyDescriptor siteNameProperty = null;
foreach (var item in items)
{
    if (siteProperty == null) {
     PropertyDescriptorCollection itemProperties = TypeDescriptor.GetProperties(item);
        siteProperty = itemProperties["Site"];
    }
    object site = siteProperty.GetValue(item);
    if (siteNameProperty == null) {
     PropertyDescriptorCollection siteProperties = TypeDescriptor.GetProperties(site);
        siteNameProperty = siteProperties["SiteName"];
    }
    object siteName = siteNameProperty.GetValue(site);
    Console.WriteLine(siteName);
}

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