使用反射获取属性

时间:2017-10-20 20:08:35

标签: c# reflection

我正在使用反射来获取一些属性,当GetValue(item,null)返回一个对象时,我遇到了问题。 我做了:

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

这样做,我得到了一个对象System.Data.Entity.DynamicProxies.Site。调试它,我可以看到该对象的所有属性,但我无法得到它。例如,一个属性是:siteName,我怎样才能得到它的值?

1 个答案:

答案 0 :(得分:0)

Entity Framework生成的DynamicProxies是POCO类的后代。也就是说,如果将结果向上转换为POCO,您实际上可以访问所有属性:

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

如果由于某种原因需要使用反射,这也是可能的:

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);
}

反射很慢,所以如果我不知道编译时的类型,我会使用TypeDescriptor:

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);
}