我有一个IndexModel基类,用于几乎所有构建实体索引表的视图模型:
public class IndexModel<TIndexItem, TEntity> : ViewModel
where TIndexItem : MappedViewModel<TEntity>, new()
where TEntity : new()
{
public IndexModel()
{
Items = new List<TIndexItem>();
}
public TIndexItem TemplateItem { get; set; }
public List<TIndexItem> Items { get; set; }
public virtual void MapFromEntityList(IEnumerable<TEntity> entityList)
{
Items = Mapper.Map<IEnumerable<TEntity>, List<TIndexItem>>(entityList);
}
}
我觉得TEntity参数是不必要的,就像TIndexItemtype一样MappedViewModel<TEntity>。我的问题是双重的:
我需要动态调用
MapFromEntityList,使用反射来确定是什么TEntity。构造IEnumerable<TEntity>参数相当简单,但Mapper.Map<IEnumerable<TEntity>, List<TIndexItem>>(entityList)调用是一个挑战。如何使用动态构建的类型参数调用 map?我的班级有约束
where : MappedViewModel<TEntity>, new()。这不是一个太大的问题,因为我可以让这个不太具体,例如where TIndexItem : ViewModel, new(),ViewModel我的所有视图模型的“无类型”基类在哪里。然后我只能做一些TEntity特定的事情,比如映射调用 ifTIndexItemis aMappedViewModel<TEntity>。