Specify allowed enum values in a property

后端 未结 4 1850
一个人的身影
一个人的身影 2021-01-11 17:24

Is it possible to specify that a enum property can only have a range of values?

enum Type
{
    None,
    One,
    Two,
    Three
}

class Object
{
    [Allo         


        
4条回答
  •  旧巷少年郎
    2021-01-11 17:29

    You could do a workaround like this:

    static MyEnumType[] allowedEnumTypes = {MyEnumType.One, MyEnumType.Two};
    
    MyEnumType _myEnumObject = allowedEnumTypes.First();
    MyEnumType MyEnumObject
    {
        get
        {
            return _myEnumObject;
        }
        set
        {
            if(!allowedEnumTypes.Any (et => et == value))
            {
                throw new Exception("Enum value not allowed.");
            }
            _myEnumObject = value;
        }
    }
    

提交回复
热议问题