How to determine if a given Integer is in a particular Enum?

后端 未结 4 1538
你的背包
你的背包 2021-02-18 20:13

In VB.NET, even with Option Strict on, it\'s possible to pass an Enum around as an Integer.

In my particular situation, someone\'s using an enum similar to

相关标签:
4条回答
  • 2021-02-18 21:03

    One option is to try something like this (in C#):

    bool isTheValueInTheEnum = System.Enum.IsDefined(typeof(Animals), animalType);
    
    0 讨论(0)
  • 2021-02-18 21:04

    There isn't a [Enum].TryParse, but there is [Enum].IsDefined which if try means your [Enum].Parse should succeed.

    You should also be able to add a None = -1 option to the Enum

    In my enums I tend to use a pattern like:

    public enum Items
    {
        Unknown = 0,
        One,
        Two, 
        Three,
    }
    

    So that a default int -> Enum will return Unknown

    Edit - Oh, looks like there is a TryParse in .Net 4. That's neat!

    0 讨论(0)
  • 2021-02-18 21:06

    Although .NET 4.0 introduced the Enum.TryParse method you should not use it for this specific scenario. In .NET an enumeration has an underlying type which can be any of the following (byte, sbyte, short, ushort, int, uint, long, or ulong). By default is int, so any value that is a valid int is also a valid enumeration value.

    This means that Enum.TryParse<Animal>("-1", out result) reports success even though -1 is not associated to any specified enumeration value.

    As other have noted, for this scenarios, you must use Enum.IsDefined method.

    Sample code (in C#):

    enum Test { Zero, One, Two }
    
    static void Main(string[] args)
    {
        Test value;
        bool tryParseResult = Enum.TryParse<Test>("-1", out value);
        bool isDefinedResult = Enum.IsDefined(typeof(Test), -1);
    
        Console.WriteLine("TryParse: {0}", tryParseResult); // True
        Console.WriteLine("IsDefined: {0}", isDefinedResult); // False
    }
    
    0 讨论(0)
  • 2021-02-18 21:12

    There is an Enum.TryParse in .NET 4.

    Although Enum.IsDefined probably suits your needs better.

    0 讨论(0)
提交回复
热议问题