从非泛型类型到泛型类型的automapper映射

时间:2017-11-28 14:28:23

标签: c# generics mapping automapper mapper

是否可以(以及如何)创建从非泛型类型到泛型类型的映射? 假设我们有:

conda install -c conda-forge keras

我尝试使用开放式泛型(https://github.com/AutoMapper/AutoMapper/wiki/Open-Generics):

public interface IFoo
{
     string Foo { get; set; }
}

public interface IGenericFoo<TDestination> where TDestination : class
{
     string Baboon { get; set; }
}

但在运行时因以下错误而失败:

  

{&#34;类型或方法有1个通用参数,但提供了0个通用参数。必须为每个通用参数提供通用参数。&#34;}

Automapper版本:4.2.1

1 个答案:

答案 0 :(得分:2)

这仅适用于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://dotnetfiddle.net/wpBp7k