开放泛型
Open Generic
public class Source<T> {
public T Value { get; set; }
}
public class Destination<T> {
public T Value { get; set; }
}
// Create the mapping
var configuration = new MapperConfiguration(
cfg => cfg.CreateMap(typeof(Source<>), typeof(Destination<>))
);
不用为封闭泛型定义映射, AutoMapper
会自动将开放泛型映射作用到封闭分型中.
var source = new Source<int> { Value = 10 };
var dest = mapper.Map<Source<int>, Destination<int>>(source);
dest.Value.ShouldEqual(10);
由于 C# 的参数必须是封闭泛型, 因此开放泛型在定义时使用 typeof
.
也可以创建开放泛型类型转换:
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap(typeof(Source<>), typeof(Destination<>))
.ConvertUsing(typeof(Converter<>))
});
开放泛型的类型转换支持多泛型参数
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap(typeof(Source<>), typeof(Destination<>))
.ConvertUsing(typeof(Converter<,>))
});