2017-11-28 22 views
0

제네릭 타입이 아닌 타입에서 제네릭 타입으로 맵을 생성하는 것이 가능합니까? 우리 가정 가 있습니다비 제너릭 타입에서 제네릭 타입으로의 오토 맵퍼 맵

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<>) 

을하지만, 다음과 같은 오류와 런타임에 실패

{"The type or method has 1 generic parameter(s), but 0 generic argument(s) were provided. A generic argument must be provided for each generic parameter."}

Automapper 버전 : 4.2.1

+1

당신이 매핑을 적용 할 때'TDestination'가있을 것으로 예상 할 : 다음은 작업 예입니다? – DavidG

+0

실제로 Mapper.Map 호출 중에 제공 할 클래스 – Koteczeg

답변

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