是否有可能(以及如何)创建从非泛型类型到泛型类型的映射?假设我们有:
public interface IFoo
{
string Foo { get; set; }
}
public interface IGenericFoo<TDestination> where TDestination : class
{
string Baboon { get; set; }
}我尝试通过这样做来使用开放的泛型(https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics):
CreateMap(typeof(IFoo), typeof(IGenericFoo<>)但在运行时失败,有以下错误:
{“类型或方法有1个泛型参数,但提供了0个泛型参数。必须为每个泛型参数提供一个泛型参数。”}
Automapper版本: 4.2.1
发布于 2017-11-29 10:13:23
这只适用于AutoMapper版本5.x及更高版本。下面是一个有用的例子:
using AutoMapper;
using System;
public class Program
{
public class Source : IFoo
{
public string Foo { get; set; }
}
public class Destination<T> : IGenericFoo<T> where T : class
{
public string Baboon { get; set; }
}
public interface IFoo
{
string Foo { get; set; }
}
public interface IGenericFoo<TDestination> where TDestination : class
{
string Baboon { get; set; }
}
public static void Main()
{
// Create the mapping
Mapper.Initialize(cfg => cfg.CreateMap(typeof(Source), typeof(Destination<>)));
var source = new Source { Foo = "foo" };
var dest = Mapper.Map<Source, Destination<object>>(source);
Console.WriteLine(dest.Baboon);
}
}https://stackoverflow.com/questions/47533986
复制相似问题