首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >自动映射从非泛型类型到泛型类型

自动映射从非泛型类型到泛型类型
EN

Stack Overflow用户
提问于 2017-11-28 14:28:23
回答 1查看 3.7K关注 0票数 0

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

代码语言:javascript
复制
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):

代码语言:javascript
复制
CreateMap(typeof(IFoo), typeof(IGenericFoo<>)

但在运行时失败,有以下错误:

{“类型或方法有1个泛型参数,但提供了0个泛型参数。必须为每个泛型参数提供一个泛型参数。”}

Automapper版本: 4.2.1

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-29 10:13:23

这只适用于AutoMapper版本5.x及更高版本。下面是一个有用的例子:

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47533986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档