简体   繁体   中英

Limit a char property to a certain set of options

C#中的哪个属性可以将public char gender限制为MFO ,否则会出现错误消息?

there is no such attribute but you can do something like this.

public class FOO 
        {
            private char _foo;
            public char foo 
            {
                get { return _foo; }
                set {
                    if (value == 'M' || value == 'F' || value == 'O')
                    {
                        _foo = value;
                    }
                    else 
                    {
                        throw new Exception("invalid Character");
                    }
              }
            }
        }

or you can try ENUM and bind it with interface as you want.

public enum Gender 
{ 
    M,
    F,
    O
}

and you can use it here

public class FOO 
{
   public Gender gender {get;set;} 

}

Enums are really good when you don't need a value to store. When you do need one (which in this case I think you do) I prefer using a public static class as follows:

public static class Gender
    {
        public const char Male = 'M';
        public const char Female = 'F';
        public const char Other = 'O';

    }

You can then use it similar to an enum but in this case you actually have a value:

Gender.Male

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM