Refering to this article every enum should have a null value, which totally makes sense. However I wanted to write a function that returns data based on the day of the week but as an optional parameter so you can get the data from all the week days if you don't provide a DayOfWeek
value. Something like the following (demonstration code):
private List<Class> GetData(DayOfWeek Day = DayOfWeek.Empty)
{
}
Run Code Online (Sandbox Code Playgroud)
As you can see here the DayOfWeek
enum doesn't provide an empty value. Obviously i can work my way around by converting the DayOfWeek to a string or an integer, but basically it feels like this DayOfWeek
enum speaks against Microsoft's own design guidelines?
Is there any reason why this enum is like it is or is this just a design flaw?
英文的文字更清晰:
非标志属性枚举应该定义一个值为 0 的成员,以便默认值是枚举的有效值。
他们的主要区别在于英语更清楚,要求为零值(不是null
,因为枚举成员不能有null
值)。
DayOfWeek
满足此要求,因为它具有Sunday
:
星期日 0 表示星期日。
这里的目的是,如果您执行类似https://dotnetfiddle.net/H4Eq1k 的代码(通过该代码声明枚举类型的变量但不为其分配任何内容,因此它具有默认的 0 值),那么您将变得有意义结果(即 0 表示枚举的有效值)。
如果您想要做的是允许一些可选的概念,DayOfWeek
那么您可能需要一个可为空的参数:
private List<Class> GetData(DayOfWeek? Day = null)
{
}
Run Code Online (Sandbox Code Playgroud)
这将允许您根据需要传递一周中的某一天(null
如果不传递值,则使用值)。
归档时间: |
|
查看次数: |
169 次 |
最近记录: |