将对象转换为泛型类型 - automapper静态扩展
问题描述:
我试图将我的AutoMapper代码转换为更流畅的API,例如 现有代码:将对象转换为泛型类型 - automapper静态扩展
Model.Foo target = Mapper.Map<Contract.Foo, Model.Foo>(source);
我想什么的代码看起来是这样的
Model.Foo target = source.ConvertTo<Model.Foo>();
我开始写我的扩展方法,但我似乎无法得到这个工作。
public static class AutoMapperConverterExtension
{
public static T ConvertTo<T>(this string source) where T : new()
{
Type sourceType = Type.GetType(source);
if (IsMapExists<sourceType, T>()) // complains here! cannot resolve 'sourceType'. If I use inline, won't compile.
{
return Mapper.Map<T>(source);
}
throw new NotImplementedException("type not supported for conversion");
}
public static bool IsMapExists<TSource, TDestination>()
{
return (AutoMapper.Mapper.FindTypeMapFor<TSource, TDestination>() != null);
}
}
答
看起来你是过于复杂的事情,你也许能蒙混过关:
public static T ConvertTo<T>(this object source)
{
return Mapper.Map<T>(source);
}
这就是说,你不能使用你正在试图做仿制药代码发布。 sourceType
是一个运行时变量,不能用于在编译时确定的泛型类型参数。在这种情况下,AutoMapper提供了一个可以使用的非通用版本FindTypeMapFor()
。
你也不能认为source
将会是一个字符串参数。你可能想要一个object
。
public static T ConvertTo<T>(this object source) where T : new()
{
Type sourceType = Type.GetType(source);
if (IsMapExists(sourceType, typeof(T)))
{
return Mapper.Map<T>(source);
}
throw new NotImplementedException("type not supported for conversion");
}
public static bool IsMapExists(Type source, Type destination)
{
return (AutoMapper.Mapper.FindTypeMapFor(source, destination) != null);
}
答
在调用泛型函数时,引发错误的行需要更改为使用反射。
var method = typeof(AutoMapperConverterExtension).GetMethod("IsMapExists");
var generic = method.MakeGenericMethod(sourceType, typeof(T));
bool exists = Convert.ToBoolean(generic.Invoke(null, null));
if (exists)
{
return Mapper.Map<T>(source);
}
+0
谢谢,我学到了一些新东西,但我标出了另一个答案是正确的,因为它更好地解决了我面临的问题。 – Raymond 2014-09-22 21:40:02
,并且您实施有什么问题? – Servy 2014-09-22 18:57:26
*抱怨这里*关于什么? – 2014-09-22 18:59:17
更新后 - 基本上不会编译。 – Raymond 2014-09-22 19:19:51