Can I add an enum to an existing .NET Structure, like Date?

可紊 提交于 2019-12-01 22:39:30

问题


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.


回答1:


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.




回答2:


You could add an extension like this:

public static class DateTimeExtension
{    
    public static Months GetMonth(this Date dt)
    {
        return (Months)dt.Month;
    }
    public static Months GetMonthStr(this Date dt)
    {
        return ((Months)dt.Month).ToString();
    }
}



回答3:


Extension method stub:

public static class DateTimeExtensions
{
   public static string GetMonthName(this DateTime dateTime)
   {
       // add using System.Globalization;
       return DateTimeFormatInfo.GetMonthName(dateTime.Month);
   }

   public static Months GetMonth(this DateTime dateTime)
   {          
         return (Months)dateTime.GetMonthName();          
   }
}

Usages:

DateTime mydate = dateTime.Now;    
string month = mydate.GetMonthName();
Months name = mydate.GetMonth();


来源:https://stackoverflow.com/questions/7903724/can-i-add-an-enum-to-an-existing-net-structure-like-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!