通用映射器调用另一个映射器

时间:2018-06-29 13:54:25

标签: c# generics mapper

在旧的应用程序中,我使用单独的映射将任何模型转换为视图模型和逆模型。 现在我要使用泛型函数,但泛型函数不能调用可见的地图

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
    }
}

我,我是通用类型的新手,请帮忙

1 个答案:

答案 0 :(得分:1)

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

如果要调用Mapper.Map(GroupDevides e)​​,则需要直接调用它,或者让Mapper.Map(q)根据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
    }
}
相关问题