c# - 动态声明一个类型作为参数传递...c#

标签 c# automapper

我在 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 个对象 im 映射的多个函数。我可以对我的对象执行 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。

最佳答案

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

Mapper.CreateMap(t, typeof(ClassTwo));

关于c# - 动态声明一个类型作为参数传递...c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19847504/

相关文章:

c# - EntityFramework 查询操作、数据库提供程序包装、数据库表达式树

c# - WPF 中的 WindowsFormsHost 不显示托管应用程序

c# - 使用 LINQ 分隔列表元素并将结果插入回列表

c# - Automapper:在映射中一起使用源和目标

automapper - 使用 LightInject 配置 AutoMapper

c# - 将 AutoMapper 与 Xamarin Sqlite 一起使用时未找到 ToList 方法

c# - MVC : model of type Nullable<T>

c# - 为什么存在 Microsoft.Office.Interop.Outlook.Exception?

asp.net-mvc - Automapper 从嵌套类映射到单个(展平)

c# - 解决方案的本地构建适用于 .NET 7,但不适用于管道