我可以将枚举添加到现有的 .NET 结构(例如日期)中吗?
显然,微软的日期结构中没有月份枚举。
我想知道的是,是否可以创建一个枚举并将其附加到 DateTime 结构?扩展方法立即浮现在我的脑海中,但我不知道如何使用它们来实现这一点。
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
有人对此有什么想法吗?
更新: 我不想获取当前月份或给定日期的月份名称。我知道该怎么做。我只是想创建一个具有 Month 属性的类,并希望使用 Enum 来表示月份。由于这似乎是一个可能在其他地方有用的项目,因此我讨厌将枚举放入我的类中,而宁愿将其“定位”在与其直接相关的结构中,以便可以轻松找到它。 感谢您的所有回复。我应该更清楚地知道我想做什么。
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?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能向这样的现有类型添加属性。
不过,您可以添加一个扩展方法,它将从整数转换为对应的枚举值,或者简单地返回月份对应的枚举值。
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.
您可以添加这样的扩展:
You could add an extension like this:
扩展方法存根:
用法:
Extension method stub:
Usages: