首页 > 解决方案 > 如何确定是否为变量分配了枚举中存在的值?

问题描述

我有这个枚举:

namespace J.Enums
{
    public enum TH
    {
        Light = 0,
        Dark = 1
    }

    public static partial class Extensions
    {
        public static string Text(this TH theme)
        {
            switch (theme)
            {
                default:
                case TH.Light: return "Light";
                case TH.Dark: return "Dark";
            }
        }

        public static TH ToTheme(this string theme)
        {
            switch (theme)
            {
                default:
                case "Light": return TH.Light;
                case "Dark": return TH.Dark;
            }
        }
    }
}

如果我有a如下变量:

var a = 88;

如何确定 a 的值是否是 Enum 的有效值?在这种情况下,它不会。

标签: c#

解决方案


var isDefined = Enum.IsDefined(typeof(TH), a);

推荐阅读