Check that integer type belongs to enum member

前端 未结 7 1300
情歌与酒
情歌与酒 2020-12-30 22:44

I want to check that some integer type belongs to (an) enumeration member.

For Example,

public enum Enum1
{
    member1 = 4,

    member2 = 5,

    m         


        
相关标签:
7条回答
  • 2020-12-30 23:17

    As Sam says, you can use IsDefined. This is somewhat awkward though. You may want to look at my Unconstrained Melody library which would let you us:

    Enum1 e2 = (Enum1)10;
    if (e2.IsNamedValue()) // Will return false
    {
    }
    

    It's probably not worth it for a single enum call, but if you're doing a lot of stuff with enums you may find some useful things in there.

    It should be quicker than Enum.IsDefined btw. It only does a linear scan at the moment, but let me know if you need that to be improved :) (Most enums are small enough that they probably wouldn't benefit from a HashSet, but we could do a binary search...)

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