开放泛型类型映射

AutoMapper 支持开放泛型类型的映射。可以直接为开放泛型创建映射关系:

public class Source<T> {
    public T Value { get; set; }
}

public class Destination<T> {
    public T Value { get; set; }
}

// 创建开放泛型映射
Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source<>), typeof(Destination<>)));Code language: PHP (php)

不需要再单独为闭合泛型类型创建映射。AutoMapper 在运行时,会把开放泛型上的配置自动应用到闭合泛型映射上。

var source = new Source<int> { Value = 10 };

var dest = mapper.Map<Source<int>, Destination<int>>(source);

dest.Value.ShouldEqual(10);Code language: JavaScript (javascript)

完整示例代码:

using AutoMapper;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建开放泛型映射
            Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source<>),typeof(Destination<>)));

            var source = new Source<int> { Value = 10 };
            var dest = Mapper.Map<Source<int>, Destination<int>>(source);

            Console.ReadKey();
        }
    }

    public class Source<T>
    {
        public T Value { get; set; }
    }

    public class Destination<T>
    {
        public T Value { get; set; }
    }
}Code language: JavaScript (javascript)

要点:

  1. Source<>Destination<> 代表开放泛型,不指定具体T类型。
  2. 只需要定义一次开放泛型映射,Source<int>Source<string> 等所有闭合泛型都可以直接复用该映射配置。
  3. 开放泛型上配置的 ForMember、Condition 等规则,运行时会自动继承到各个闭合泛型。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注