Using an enum as an optional parameter

前端 未结 3 673
花落未央
花落未央 2020-12-31 00:27

I have several methods in an application I\'m working on loaded with optional parameters, some of which are enums. Currently, in order to do that I\'m writing methods with a

相关标签:
3条回答
  • 2020-12-31 01:01

    What about :

    enum MyEnum {
       MISSING = -1,
       FirstValue,
       SecondValue,
       ...
    }
    
    public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum myThirdParam = MISSING) {
         if (myThirdParam != MISSING)
         {
              //do something with it
         }
    } 
    
    0 讨论(0)
  • 2020-12-31 01:17

    I would suggest using nullable enum in this situation, like this:

    public void SomeMethod(string myFirstParam = "", 
                           string mySecondParam = "", 
                           MyEnum? myThirdParam = null)
    {
       if (myThirdParam.HasValue)
       {
          var enumValue = myThirdParam.Value;
          //do something with it
       }
    }
    

    and you can use it like this:

    SomeMethod(myThirdParam: MyEnum.Something);
    
    0 讨论(0)
  • 2020-12-31 01:18

    Make sure your enum has a default value (equal to zero), that means "none" or "invalid". This would be an appropriate value for your optional parameter's default value.

    This is recommended by Microsoft Code Analysis as well, CA1008: Enums should have zero value.

    For example:

    enum SpeakerType
    {
        None = 0,
        Woofer,
        Midrange
        Tweeter
    }
    

    This way the default keyword provides a value that is sane, but doesn't unintentionally refer to something you don't want it to.


    As an example, the BCL uses this same concept. The number of stop bits to use for a SerialPort is defined by the StopBits enum:

    public enum StopBits
    {
      None,
      One,
      Two,
      OnePointFive,
    }
    

    However the None value is invalid. In fact,

    The SerialPort class throws an ArgumentOutOfRangeException exception when you set the StopBits property to None.

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