【问题标题】:generic mapper call another mapper通用映射器调用另一个映射器
【发布时间】:2018-06-29 13:54:25
【问题描述】:

在旧应用程序中,我使用单独的地图将任何模型转换为视图模型并反转。 现在我想使用泛型函数,但泛型函数不调用视觉映射

public class GenericBll<TVModel, TMModel> where TVModel : class where TMModel : class
{
    public virtual IEnumerable<TVModel> GetAll()
    {
        var a = Instance.GetAll_asQuery().ToList();
        var b = a.Select(q=> Mapper.Map<TVModel,TMModel>(q)).ToList();
        //mapper not return true thing
        return b;
    }
}

这是我的通用映射器

public partial class Mapper
{
    internal static TVModel Map<TMModel>(TMModel q)  where TMModel : class where TVModel : class
    {
    //want to this function call another but always run this :(
        throw new NotImplementedException();
    }

    public static MM.GroupDevides Map(GroupDevides e)
    {
        //map to MM.GroupDevides
    }
    public static GroupDevides Map(MM.GroupDevides e)
    {
         //map to GroupDevides
    }
}

我是泛型类型的新手,请帮忙

【问题讨论】:

  • Automapper 会开箱即用你知道吗?
  • @Liam 是的,但我说它会减慢程序而不是测试

标签: c# generics mapper


【解决方案1】:

我不确定您要做什么,但是如果您想调用 Mapper.Map(q),其中 q 的类型为 GroupDevides 某处,它使用泛型方法并将转换为 TMModel 的参数传递。

如果要调用Mapper.Map(GroupDevides e),需要直接调用或者根据q的类型让Mapper.Map(q)调用。 代码看起来像这样:

class Mapper
{
    public static object Map<TMModel>(TMModel q) where TMModel : class
    {
        MethodInfo methodInfo = typeof(Mapper).GetMethod("Map", new Type[] { q.GetType() });

        if (methodInfo != null)
            return methodInfo.Invoke(null, new object[] { q });

        return null;
    }

    public static GroupDevides Map(MM.GroupDevides e)
    {
        //map to GroupDevides
    }
}

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 2022-08-03
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多