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 IItemListable
{
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:
Edit: I would better mark ChildItems as virtual in the base then you could write
and
without any need to cast, avoiding the use of the new keyword and without having to use reflection.