vendredi 16 septembre 2016

Use reflection for casting to unknown type

In my action I do something like this:

public ActionResult Overview(IDynamicList entity, int skip, int take)
{
    List<IEntityModel> model = getModel(entity.GetTypeName(), skip, take); 

    string viewName = entity.GetView();

    return PartialView(viewName, model);
}

private List<IEntityModel> getModel(string typeName, int skip, int take)
{
    string getComponentsMethodName = nameof(IContentQueryProvider.GetComponents).Split('.').Last();

    Type typeOfEntity = FindViewModelByTitle<IContentModelAttribute>(typeName);

    var data =
        typeof(IContentQueryProvider)
        .GetMethod(getComponentsMethodName, new Type[] { typeof(int), typeof(int) })
        .MakeGenericMethod(new[] { typeOfEntity })
        .Invoke(_contentQueryProvider, new object[] { skip, take });

    return (data as IEnumerable<object>).OfType<IEntityModel>().ToList();
}

I want to cast the return object to List<typeOfEntity> instead, however the only thing I know is that typeOfEntity implements an interface that inherits IEntityModel. That's the reason I know that I can return List<IEntityModel> but then I can't get help from the intellisense later on in my views and I need to cast the model directly in my view instead. So how do I do the casting directly here in my controller so I can return something that makes sense directly upon arrival to the view?





Aucun commentaire:

Enregistrer un commentaire