You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将泛型类型Foo<T>(T为枚举)映射至非泛型类型Bar?

实现从Foo<T>到Bar的映射(T为枚举类型)

你需要将泛型类Foo<T>(其中T固定为枚举类型)映射到Bar类,并将Bar.Type设置为枚举T的类型名称,以下是两种可行的实现方式:

方案一:手动编写映射逻辑

直接通过扩展方法实现转换,逻辑简单且无需依赖第三方库:

// 定义扩展方法,约束T为枚举类型
public static class FooExtensions
{
    public static Bar ToBar<T>(this Foo<T> foo) where T : Enum
    {
        return new Bar
        {
            // 获取枚举的类型名称(不含命名空间)
            Type = typeof(T).Name
            // 若需要包含命名空间的完整名称,替换为 typeof(T).FullName
        };
    }
}

使用示例

// 假设有一个名为OrderStatus的枚举
var fooInstance = new Foo<OrderStatus>();
Bar barInstance = fooInstance.ToBar();
// barInstance.Type 将等于 "OrderStatus"

方案二:使用AutoMapper实现映射

如果项目中已使用AutoMapper,可通过配置泛型映射规则来实现:

  1. 确保已安装AutoMapper NuGet包
  2. 创建映射配置类:
public class FooBarMappingProfile : Profile
{
    public FooBarMappingProfile()
    {
        // 配置泛型Foo<T>到Bar的映射
        CreateMap(typeof(Foo<>), typeof(Bar))
            .ForMember(dest => dest.Type, opt => 
                opt.MapFrom(src => src.GetType().GetGenericArguments()[0].Name));
    }
}
  1. 初始化Mapper并使用:
// 初始化配置
var mapperConfig = new MapperConfiguration(cfg => 
    cfg.AddProfile<FooBarMappingProfile>());
IMapper mapper = mapperConfig.CreateMapper();

// 执行映射
var fooInstance = new Foo<OrderStatus>();
Bar barInstance = mapper.Map<Bar>(fooInstance);

额外说明

  • 如果需要的是枚举值的名称而非枚举类型名称,可调整映射逻辑(比如使用Enum.GetName(typeof(T), default(T))),但根据需求,这里我们获取的是枚举的类型名称。
  • 手动映射方案更轻量,适合简单场景;AutoMapper方案更适合已有大量映射需求的项目,便于统一管理映射规则。

内容的提问来源于stack exchange,提问作者Ivan-Mark Debono

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:55:22