In my CMS I have a load of modules which allow me to do some clever item listing stuff. I am trying to use them to pull out a list of their child objects via reflection, but am getting stuck with the level of generics involved.
I have got as far as this method:
var myList = moduleObj.GetType().GetMethod("ChildItems").Invoke(moduleObj, new object[] { });
which returns a List. Each modulespecificobject is bound it an IItemListable interface which has the methods in it I am trying to access.
I am unsure how I can cast or iterate the myList object as a set of IItemListable objects access the methods required.
Thanks
A few of the classes:
public interface IItemLi开发者_Python百科stable
{
IQueryable GetQueryableList();
string GetIDAsString();
IItemListable GetItemFromUrl(string url, List<IItemListable> additionalItems);
bool IsNewItem();
IItemListable CreateItem<T>(ItemListerControl<T> parentList) where T : class, IItemListable;
IItemListable LoadItem(string id);
IItemListable SaveItem();
RssToolkit.Rss.RssItem ToRssItem();
void DeleteItem();
string ItemUrl();
}
public interface IItemListModule<T> where T: IItemListable
{
List<T> ChildItems();
}
public class ArticlesModule : ItemListModuleBase<Article>, IItemListModule<Article>
{
#region IItemListModule<Article> Members
public new List<Article> ChildItems()
{
return base.ChildItems().Cast<Article>().Where(a => a.IsLive).ToList();
}
#endregion
}
You can direct cast while iterating:
IList myList = (IList)moduleObj.GetType().GetMethod(
"ChildItems").Invoke(moduleObj, new object[] { });
foreach (IItemListable o in myList)
{
}
Edit: I would better mark ChildItems as virtual in the base then you could write
public override List<Article> ChildItems()
{
return base.ChildItems().Where(a => a.IsLive).ToList();
}
and
var myList = moduleObj.ChildItems();
foreach (IItemListable o in myList)
{
}
without any need to cast, avoiding the use of the new keyword and without having to use reflection.
Maybe this will help:
http://devlicio.us/blogs/louhaskett/archive/2007/06/13/how-to-cast-between-list-t-s.aspx
(Also some extra links in the comments)
精彩评论