可以将枚举添加到现有的.NET结构中,例如Date? [英] Can I add an enum to an existing .NET Structure, like Date?

查看:104
本文介绍了可以将枚举添加到现有的.NET结构中,例如Date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,Microsoft在其Date日期结构中没有一个月份枚举。

我想知道的是,是否可以创建枚举并将其附加到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

有任何想法吗?

更新:
我没有尝试获取当前月份或给定日期的月份名称。我知道怎么做我只是试图创建一个有一个Month属性的类,并希望使用一个枚举代表一个月。既然这似乎是一个可以在别的地方有用的东西,我讨厌把这个枚举放在我的课上,而是把它放在与它直接相关的结构中,以便它可以很容易地找到。
谢谢你的回复。

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.

这篇关于可以将枚举添加到现有的.NET结构中,例如Date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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