Skip to main content
 首页 » 编程设计

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

2024年02月13日14sky-heaven

我在 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));