我可以添加一个枚举到现有的.NET结构,如日期?日期、结构、NET

2023-09-03 05:41:18 作者:双马尾

因此​​很明显,微软并没有一个枚举月在他们的数据结构。 我想知道的是,是有可能创造一个枚举并将其连接到一个DateTime结构?扩展方法来瞬间在脑海,但我不知道的方式使用它们来完成这件事。

So apparently Microsoft does not have a Months Enum on their Date structure. What I am wondering is, is it possible to create an enum and attach it to the DateTime structure? Extension Methods come instantly to mind, but I don't know of a way to pull this off using them.

Dim july As DateTime.Months = DateTime.Months.July

Public Enum Months
    January = 1
    February = 2
    March = 3
    April = 4
    May = 5
    June = 6
    July = 7
    August = 8
    September = 9
    October = 10
    November = 11
    December = 12
End Enum

任何一个对此有什么想法?

Any one have any thoughts on this?

更新: 我不是想获得当月的特定日期或月份名称。我知道该怎么做。我只是想创建一个类,有一个月的财产,想用枚举月份重新present。由于这似乎是可能有用处其他地方的项目,我讨厌把枚举到我的班,宁愿有它在,它直接关系到这样就可以很容易地找到结构落户。 感谢您对所有的答复。我本来应该更清楚前面是什么,我想做的事。

Update: I am not trying to get the Month name of the current Month or of a given date. I know how to do that. I was just trying to create a class that had a Month property and wanted to use an Enum to represent the month. Since this seems like an item that could have usefulness elsewhere, I hate to put the Enum into my class and would rather have it be "located" in the structure that it is directly related to so that it could be found easily. Thank you for all the responses. I should have been more clear up front as to what I wanted to do.

推荐答案

您不能到现有的类型那样添加属性。

You can't add properties to an existing type like that.

可以,但是添加扩展方法会从整数转换为相应的枚举值,或简单地返回相应月份的枚举值。

You can, however add an extension method that will convert from integers to the corresponding Enum value, or simply return the enum value corresponding to the month.

 
精彩推荐