有时我可以让AutoMapper返回相同的对象吗? [英] Can I get AutoMapper to return the same object sometimes?

查看:166
本文介绍了有时我可以让AutoMapper返回相同的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用AutoMapper在接口和该接口的具体实现之间进行映射.我假设如果传递给AutoMapper的Map<TDestination>方法的类型与返回类型相同,则将返回原始对象(作为一种短路操作).我的假设是错误的:的确,在查看之后,我注意到该方法的文档明确指出:

I've been using AutoMapper to map between an interface and a concrete implementation of that interface. I assumed that if the type that I passed in to AutoMapper's Map<TDestination> method was the same as the return type, then the original object would be returned (as a sort of short-circuiting operation). My assumption was wrong: indeed, after looking I noticed the documentation for that method explicitly states:

执行从源对象到 new 目标对象的映射.从源对象推断出源类型. (加粗强调)

Execute a mapping from the source object to a new destination object. The source type is inferred from the source object. (bold emphasis mine)

我打开了这个快速控制台应用程序只是为了验证:

I knocked-up this quick console app just to verify:

using System;
using AutoMapper;

namespace ConsoleApplication
{
    class Program
    {
        interface IFoo
        {
            string Bar { get; }
        }

        class Foo : IFoo
        {
            public string Bar { get; set; }
        }

        static void Main(string[] args)
        {
            Mapper.CreateMap<IFoo, Foo>();
            IFoo a = new Foo { Bar = "baz" };
            Foo b = Mapper.Map<Foo>(a);
            Console.WriteLine(Object.ReferenceEquals(a, b));  // false
        }
    }
}

现在,我知道此行为,因此可以针对我的特定用例对其进行优化,但是我想知道是否存在另一种使用AutoMapper的方式,该方式将以上述方式短路"(即.如果类型与我想要的目标类型相同,还给我原始对象吗?

Now that I know about this behaviour I can optimize around it for my particular use-case, but I was wondering if there is an alternate way of using AutoMapper whereby it will "short-circuit" in the way described above (ie. give me back the original object if the type is the same as the target type that I want)?

推荐答案

您可以使用Mapper.Map<TSource,TDestination>(source, destination)重载.

 Foo b = new Foo();
 Mapper.Map<IFoo,Foo>(a,b);

AutoMapper将使用b而不构建新对象.总体而言,您可以在Mapper.Map周围使用包装器,这种替代方法可能更好(未经测试):

AutoMapper will use b and not build a new object. Overall you can use a wrapper around Mapper.Map, this alternative way can be better (not tested):

public class MyMapper
{

        public static TDestination Map<TDestination>(object source) where TDestination : class
        {
            if(source is TDestination)
            {
                return (TDestination) source; //short-circuit here
            }

            return Mapper.Map<TDestination>(source);
        }


        public static TDestination Map<TSource, TDestination>(TSource source, TDestination destination)
        {
            return Mapper.Map<TSource, TDestination>(source, destination);
        }
}

这篇关于有时我可以让AutoMapper返回相同的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆