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

后端 未结 4 1604
你的背包
你的背包 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: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!

提交回复
热议问题