我有一个抽象类,它看起来像这样:使用反射和getValue问题
public abstract class PageObjectsBase
{
public abstract string FriendlyName { get; }
public abstract string PageObjectKeyPrefix { get; }
public abstract string CollectionProperty { get; }
}
以及从PageObjectsBase派生的类:
public class PageRatingList : PageObjectsBase
{
public IList<PageRating> PageRatings { get; set; }
public PageRatingList()
{
this.PageRatings = new List<PageRating>();
}
public override string CollectionProperty
{
get
{
var collectionProperty = typeof(PageRatingList).GetProperties().FirstOrDefault(p => p.Name == "PageRatings");
return (collectionProperty != null) ? collectionProperty.Name : string.Empty;
}
}
public override string FriendlyName
{
get
{
return "Page feedback/rating";
}
}
public override string PageObjectKeyPrefix
{
get
{
return "pagerating-";
}
}
}
和PageRatingList.PageRatings是持有PageRating类以下集合:
public class PageRating : PageObjectBase
{
public int Score { get; set; }
public string Comment { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
PageRatingList正在存储在数据库中(EPiS erver的动态数据存储,更具体地说使用页面对象管理器)。我需要创建一些报告功能,并且实质上是加载从PageObjectBase派生的所有报告。当涉及到返回数据时,代码在编译时永远不会知道它要加载的数据类型,所以我使用了Reflection。在我的报告I类有:
//this gives me the right type
var type = Type.GetType("MyNameSpace.PageRatingList", true);
var startPageData = this._contentRepository.Get<PageData>(startPage);
PageObjectManager pageObjectManager = new PageObjectManager(startPageData);
//this loads the instances from the DB
var props = pageObjectManager.LoadAllMetaObjects()
.FirstOrDefault(o => o.StoreName == "Sigma.CitizensAdvice.Web.Business.CustomEntity.PageRatingList");
//this gives me 4 PropertyInfo objects (IList: PageRatings, string : CollectionProperty, string :FriendlyName, string : PageObjectKeyPrefix)
var properties = props.Value.GetType().GetProperties();
我可以通过的PropertyInfo对象使用然后遍历:
foreach (var property in properties)
{
//extract property value here
}
我遇到的问题是,我无法弄清楚如何让每一个的值属性信息对象。另外,其中一个属性是List类型,我们再次不知道T的类型,直到运行时。所以我还需要一些逻辑来检查PropertyInfo对象中的一个是否为List类型,然后提供对List中每个属性的访问权限 - 列表类型为PageRating。
任何人都可以帮忙吗?我过去并没有真正使用过反射,所以我正在通过它,无论是对还是错!
非常感谢 铝
我不确定发布与我所写的答案完全相同的答案的确切时间点,但是之后半小时。 – varocarbas
呃...相同,相同,不是。实际上你的代码不能编译,因为GetValue至少需要两个参数(你甚至没有测试代码?)。每次更加困惑你的参与的确切点在这里。 – varocarbas