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

做~自己de王妃 提交于 2019-12-01 21:03:06

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:

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();
    }
}

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