使用枚举作为可选参数 [英] Using an enum as an optional parameter

查看:273
本文介绍了使用枚举作为可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的应用程序中有几种方法,这些方法中装有可选参数,其中一些是枚举.目前,为此,我正在编写具有类似签名类型的方法:

public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum myThirdParam = (MyEnum )(-1)){

     if (myThirdParam != (MyEnum ) (-1))
     {
          //do something with it
     }
}

所以我的第一个问题是,我尚未意识到这种方法是否存在一些陷阱,但是随着时间的流逝,它会痛苦地意识到这一点,其次,是否有一种更合适的解决方案,或者至少是一种优雅的解决方案? >

我应该说,我们控制此方法的输入,该输入在内部使用,因此我不担心有人投值-1来使作品更加美观.

解决方案

请确保您的enum具有默认值(等于零),表示无"或无效".对于您可选参数的默认值来说,这将是一个适当的值.

Microsoft Code Analysis也建议使用此方法, CA1008:枚举应为零值.

例如:

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

通过这种方式 default关键字提供的值是理智,但并非无意间提到了您不想要的东西.


作为示例,BCL使用相同的概念. SerialPort StopBits 枚举:

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

但是None值无效.实际上,

StopBits属性设置为None时,SerialPort类将引发ArgumentOutOfRangeException异常.

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 similar type of signature:

public void SomeMethod(string myFirstParam = "", string mySecondParam = "", MyEnum myThirdParam = (MyEnum )(-1)){

     if (myThirdParam != (MyEnum ) (-1))
     {
          //do something with it
     }
}

So my first question is, is there some pitfall to this approach I haven't realized, but in time will become painfully aware of, and secondly, is there a more proper - or at least elegant solution to it?

I should say that we control the input to this method, it's used internally, so I'm not worried about someone casting in a value of -1 to gum up the works.

解决方案

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.

这篇关于使用枚举作为可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆