Specify allowed enum values in a property

后端 未结 4 1821
一个人的身影
一个人的身影 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:32

    Same as st4hoo's solution, only with reflection. You can make it as crazy as you would like.

    using System;
    using System.Linq;
    
    namespace ConceptApplication
    {
        static class Program
        {
            static void Main(string[] args)
            {
                var foobar = new Foobar
                {
                    SomeProperty = Numbers.Five
                };
            }
        }
    
        public class Foobar
        {
            private static Numbers _someProperty;
    
            [NumberRestriction(Allowed = new[] {Numbers.One, Numbers.Two})]
            public Numbers SomeProperty
            {
                get { return _someProperty; }
                set
                {
                    RestrictionValidator.Validate(this, "SomeProperty", value);
    
                    _someProperty = value;
                }
            }
        }
    
        public class NumberRestriction : Attribute
        {
            public Numbers[] Allowed { get; set; }
        }
    
        public static class RestrictionValidator
        {
            public static void Validate(T sender, string propertyName, Numbers number)
            {
                var attrs = sender.GetType().GetProperty(propertyName).GetCustomAttributes(typeof(NumberRestriction), true);
    
                if (attrs.OfType().Any(attr => !(attr).Allowed.Contains(number)))
                    throw new ArgumentOutOfRangeException();
            }
        }
    
        public enum Numbers
        {
            One,
            Two,
            Three,
            Four,
            Five
        }
    }
    

提交回复
热议问题