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

C# 如何创建可存储2种及以上enum枚举类型值的List集合?

问题解答

完全可以实现该需求,C#中所有枚举类型都隐式继承自System.Enum抽象类,基于该特性有两类常用实现方案:


方案1:直接使用List<Enum>(最简便,适配绝大多数场景)

直接用System.Enum作为List的泛型参数即可存储任意枚举实例,写法和你期望的逻辑完全匹配:

// 声明可存储任意枚举的集合
List<Enum> myList = new List<Enum>();
// 添加不同类型的枚举实例
myList.Add(eUnit.Warrior);
myList.Add(eItem.Pizza);

// 类型判断逻辑和示例完全一致
if(myList[0].GetType() == typeof(eUnit))
{
    DoStuff();
    // 需要使用具体枚举值时直接强制转换即可
    eUnit currentUnit = (eUnit)myList[0];
}

// 更推荐的简化写法,判断类型的同时完成转换,避免二次操作
if (myList[0] is eUnit warrior)
{
    Console.WriteLine($"当前单位类型:{warrior}");
}

注意:该方案存入枚举时会产生装箱开销,普通业务场景下该性能损耗可完全忽略。


方案2:自定义无装箱封装(性能敏感场景可选)

如果是高频调用的性能敏感场景,可以自定义结构体封装枚举信息避免装箱:

// 枚举包装结构体
public struct EnumWrapper
{
    public Type EnumType { get; }
    public int RawValue { get; }

    public EnumWrapper(Enum enumVal)
    {
        EnumType = enumVal.GetType();
        RawValue = Convert.ToInt32(enumVal);
    }

    // 快速转换为对应枚举类型
    public T? As<T>() where T : Enum
    {
        return typeof(T) == EnumType ? (T)Enum.ToObject(typeof(T), RawValue) : default;
    }
}

// 使用示例
List<EnumWrapper> myList = new List<EnumWrapper>();
myList.Add(new EnumWrapper(eUnit.Warrior));
myList.Add(new EnumWrapper(eItem.Pizza));

// 取值判断
var unitVal = myList[0].As<eUnit>();
if (unitVal != null)
{
    DoStuff();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:54:01