C# 将对象转换为泛型类型-自动映射静态扩展
我正在尝试将我的AutoMapper代码转换为更流畅的api,例如。 现行守则:C# 将对象转换为泛型类型-自动映射静态扩展,c#,generics,automapper,C#,Generics,Automapper,我正在尝试将我的AutoMapper代码转换为更流畅的api,例如。 现行守则: Model.Foo target = Mapper.Map<Contract.Foo, Model.Foo>(source); Model.Foo target=Mapper.Map(源代码); 我希望代码是这样的 Model.Foo target = source.ConvertTo<Model.Foo>(); Model.Foo target=source.ConvertTo();
Model.Foo target = Mapper.Map<Contract.Foo, Model.Foo>(source);
Model.Foo target=Mapper.Map(源代码);
我希望代码是这样的
Model.Foo target = source.ConvertTo<Model.Foo>();
Model.Foo target=source.ConvertTo();
我开始写我的扩展方法,但我似乎无法让它工作
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);
}
}
公共静态类AutoMapperConverterExtension
{
公共静态T ConvertTo(此字符串源),其中T:new()
{
Type sourceType=Type.GetType(source);
if(IsMapExists())//此处有问题!无法解析“sourceType”。如果使用内联,将无法编译。
{
返回Mapper.Map(源);
}
抛出新的NotImplementedException(“不支持转换的类型”);
}
公共静态布尔IsMapExists()
{
返回(AutoMapper.Mapper.FindTypeMapFor()!=null);
}
}
看起来你把事情搞得太复杂了,你或许可以逃脱:
public static T ConvertTo<T>(this object source)
{
return Mapper.Map<T>(source);
}
看起来你把事情搞得太复杂了,你也许可以逃脱:
public static T ConvertTo<T>(this object source)
{
return Mapper.Map<T>(source);
}
在调用泛型函数时,引发错误的行需要更改为使用反射
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);
}
var method=typeof(AutoMapperConverterExtension).GetMethod(“IsMapExists”);
var generic=method.MakeGenericMethod(sourceType,typeof(T));
bool exists=Convert.ToBoolean(generic.Invoke(null,null));
如果(存在)
{
返回Mapper.Map(源);
}
调用泛型函数时,抛出错误的行需要更改为使用反射
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);
}
var method=typeof(AutoMapperConverterExtension).GetMethod(“IsMapExists”);
var generic=method.MakeGenericMethod(sourceType,typeof(T));
bool exists=Convert.ToBoolean(generic.Invoke(null,null));
如果(存在)
{
返回Mapper.Map(源);
}
您的实现遇到了什么问题?这里抱怨什么?更新了帖子基本上不会编译。您的实现遇到了什么问题?这里抱怨什么?更新了帖子基本上不会编译。谢谢,我学到了一些新东西,谢谢,我学到了一些新的东西,但是我把另一个答案标记为正确,因为它更好地解决了我面临的问题。