简体   繁体   中英

How can I determine if a variable is assigned a value that is present in an Enum?

I have this Enum:

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;
            }
        }
    }
}

If I have a variable a as follows:

var a = 88;

How can I determine if the value of a is a valid value for the Enum? Which in this case, it won't be.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM