![](/img/trans.png)
[英]Map generic type that receives constructor parameters with Automapper
[英]AutoMapper determine what to map based on generic type
有沒有一種方法可以為AutoMapper僅提供一個源,並根據指定的映射為該源的類型自動確定要映射的對象?
例如,我有一個Foo類型,我一直希望它映射到Bar,但是在運行時,我的代碼可以接收許多泛型類型中的任何一個。
public T Add(T entity)
{
//List of mappings
var mapList = new Dictionary<Type, Type> {
{typeof (Foo), typeof (Bar)}
{typeof (Widget), typeof (Sprocket)}
};
//Based on the type of T determine what we map to...somehow!
var t = mapList[entity.GetType()];
//What goes in ?? to ensure var in the case of Foo will be a Bar?
var destination = AutoMapper.Mapper.Map<T, ??>(entity);
}
任何幫助深表感謝。
正如@tobsen所說,非通用重載是您需要的:
public T Add(T entity)
{
//List of mappings
var mapList = new Dictionary<Type, Type> {
{typeof (Foo), typeof (Bar)}
{typeof (Widget), typeof (Sprocket)}
};
Type sourceType = typeof(T);
Type destinationType = mapList[sourceType];
object destination = AutoMapper.Mapper.Map(entity, sourceType, destinationType);
// ... rest of code
}
以我的經驗,僅當您事先知道源/目標類型時,泛型重載才有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.