1

我在 VS2012 中使用 AutoMapper。这是我使用的 autoMapper 方法的签名:

         public static IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>();

它接受两种类型作为参数,将类型#1 映射到类型#2 并返回类型#2。我有一堆类都继承自同一个源。如果我尝试创建 AutoMap 实例,我必须执行以下操作:

            Mapper.CreateMap<ClassOne, ClassTwo>();  
            ClassOne one = new ClassOne{Name="One};
            ClassTwo two = Mapper.Map<ClassOne, ClassTwo>(one);

这会将 ClassOne 对象中的所有字段“映射”到我的 ClassTwo 对象(是的 ClassTwo 具有 ClassOne 的一些字段)。我想设置一个函数,该函数将调用 Mapper 函数将一个对象映射到另一个对象,而不是使用相同代码的多个函数,仅更改 2 个对象即时映射。我可以对我的对象执行 GetType() 并具有我需要的字符串格式的类型:

         ClassOne one = new ClassOne();
         Type t = one.GetType();
         var type = t.FullName; //type is now "Generic.Collection.ClassOne"
         Mapper.CreateMap<type, ClassTwo>();//this will not compile
         Mapper.CreateMap<one.GetType(), ClassTwo>();//neither will this

但我不能将字符串传递给 Mapper 函数。如何动态声明类型?

我使用 AutoMapper 作为我想如何声明和使用类型的示例。我还有其他功能可以做同样的事情。所以我的问题是如何动态声明类型?- 不是如何使用 AutoMapper。

4

2 回答 2

3

CreateMap 方法还有另一个非泛型重载:

Mapper.CreateMap(t, typeof(ClassTwo));
于 2013-11-07T22:01:45.417 回答
1

您使用错误的自动映射器。

Automapper 旨在在应用程序引导时进行配置,以设置 Mapper.CreateMap 的类型注册表,其中 T1 和 T2 是类型,而不是实例。您可以使用字符串重载将两种类型映射在一起,这样就可以了。自动映射器注册表不是线程安全的,因此请确保在应用程序开始时将其连接起来,而不是在遇到正在使用的类型时懒惰地/。

配置自动映射器后,只需在常规代码中使用 Mapper.Map。

于 2013-11-07T22:03:52.980 回答