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

C#如何根据enum枚举值获取对应类的Type类型

实现方案

下面提供两种常用的实现方式,可根据你的业务场景选择:

方案1:Switch 硬编码匹配(适用于枚举项较少的场景)

这种方式性能最高,无需额外依赖,编译期即可验证类型正确性,是最稳妥的实现:

public Type GetObjectType(Types type)
{
    return type switch
    {
        Types.A => typeof(A),
        Types.B => typeof(B),
        _ => throw new ArgumentOutOfRangeException(nameof(type), type, "当前枚举值未配置对应类型映射")
    };
}

如果使用的是不支持switch表达式的低版本C#,可以改用传统switch case写法:

public Type GetObjectType(Types type)
{
    switch (type)
    {
        case Types.A:
            return typeof(A);
        case Types.B:
            return typeof(B);
        default:
            throw new ArgumentOutOfRangeException(nameof(type), type, "当前枚举值未配置对应类型映射");
    }
}

方案2:特性标注+反射映射(适用于枚举项多、迭代频繁的场景)

如果后续枚举项会不断新增,不想每次都修改switch代码,可以通过给枚举项加自定义特性的方式解耦映射关系:

  1. 首先定义类型映射特性类
[AttributeUsage(AttributeTargets.Field)]
public class TypeMappingAttribute : Attribute
{
    public Type TargetType { get; }
    public TypeMappingAttribute(Type targetType)
    {
        TargetType = targetType ?? throw new ArgumentNullException(nameof(targetType));
    }
}
  1. 给枚举项添加特性标记
public enum Types
{
    [TypeMapping(typeof(A))]
    A = 1,
    [TypeMapping(typeof(B))]
    B = 2
}
  1. 实现反射读取的方法,这里提供带静态缓存的优化版本,避免每次调用都执行反射消耗性能:
// 静态缓存存储枚举到类型的映射,程序启动时仅初始化一次
private static readonly IReadOnlyDictionary<Types, Type> _typeMappingCache;

// 所在类的静态构造函数,初始化缓存
static 你当前的类名() // 这里替换为你GetObjectType方法所在的类的名称
{
    _typeMappingCache = Enum.GetValues<Types>()
        .ToDictionary(
            enumVal => enumVal,
            enumVal =>
            {
                var mappingAttr = typeof(Types)
                    .GetMember(enumVal.ToString())
                    .First()
                    .GetCustomAttribute<TypeMappingAttribute>();
                if (mappingAttr == null)
                    throw new InvalidOperationException($"枚举值{enumVal}未配置TypeMapping特性");
                return mappingAttr.TargetType;
            });
}

public Type GetObjectType(Types type)
{
    if (_typeMappingCache.TryGetValue(type, out var targetType))
        return targetType;
    throw new ArgumentOutOfRangeException(nameof(type), type, "当前枚举值未配置对应类型映射");
}

内容的提问来源于stack exchange,提问作者ANDU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:24:03