[英]AutoMapper mapping with generic extension methods
我想用通用擴展方法映射我的對象。
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Address HomeAddress { get; set; }
public string GetFullName()
{
return string.Format(“{0} {1}”, FirstName, LastName);
}
}
這是viewmodel
public class CustomerListViewModel
{
public string FullName { get; set; }
public string Email { get; set; }
public string HomeAddressCountry { get; set; }
}
所以我創建了map, Mapper.CreateMap<Customer, CustomerListViewModel>();
我想創建一個擴展方法
public static class MapperHelper
{
public static CustomerListViewModel ToViewModel(this Customer cust)
{
return AutoMapper.Mapper.Map<Customer, CustomerListViewModel>(cust);
}
}
但我想制作通用的幫手:
public static class MapperHelper<TSource, TDest>
{
public static TDest ToViewModel(this TSource cust)
{
return AutoMapper.Mapper.Map<TSource, TDest>(cust);
}
}
給出錯誤: 擴展方法只能在非泛型的非嵌套靜態類中聲明
如果我不能創建泛型,我應該為所有映射創建幫助類。 有什么方法可以解決嗎?
甚至比這些解決方案更好的是使用非通用Map方法:
public static class MapperHelper
{
public static TDest MapTo<TDest>(this object src)
{
return (TDest)AutoMapper.Mapper.Map(src, src.GetType(), typeof(TDest));
}
}
在你的代碼中:
var model = customter.MapTo<CustomerViewModel>();
現在,您不需要泛型方法中的多余Source類型。
你不能這樣做嗎?:
public static class MapperHelper
{
public static TDest ToViewModel<TSource, TDest>(this TSource cust)
{
return AutoMapper.Mapper.Map<TSource, TDest>(cust);
}
}
您無法在泛型類中定義擴展方法,因為在調用它時無法指定類型參數!
public static class MapperHelper<TSource, TTarget>
{
public static TTarget ToViewModel(this TSource source)
{
...
}
}
...
// this is no problem if we invoke our method like a
// static method:-
var viewModel = MapperHelper<MyModel, MyViewModel>.ToViewModel(model);
// but if we use the extension method syntax then how
// does the compiler know what TSource and TTarget are?:-
var viewModel = model.ToViewModel();
你必須使方法變得通用: -
public static class MapperHelper
{
public static TTarget ToViewModel<TSource, TTarget>(this TSource source)
{
...
}
}
...
var viewModel = model.ToViewModel<MyModel, MyViewModel>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.