Validate Enum Values

前端 未结 11 1005
你的背包
你的背包 2020-11-30 09:43

I need to validate an integer to know if is a valid enum value.

What is the best way to do this in C#?

11条回答
  •  没有蜡笔的小新
    2020-11-30 10:09

    As others have mentioned, Enum.IsDefined is slow, something you have to be aware of if it's in a loop.

    When doing multiple comparisons, a speedier method is to first put the values into a HashSet. Then simply use Contains to check whether the value is valid, like so:

    int userInput = 4;
    // below, Enum.GetValues converts enum to array. We then convert the array to hashset.
    HashSet validVals = new HashSet((int[])Enum.GetValues(typeof(MyEnum)));
    // the following could be in a loop, or do multiple comparisons, etc.
    if (validVals.Contains(userInput))
    {
        // is valid
    }
    

提交回复
热议问题