Can't create static variable inside a static method?

前端 未结 4 1106
夕颜
夕颜 2021-01-24 23:44

Why won\'t this work?

public static int[] GetListOfAllDaysForMonths()
{
    static int[] MonthDays = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,2         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-25 00:33

    C# doesn't support static locals at all. Anything static needs to be a member of a type or a type itself (ie, static class).

    Btw, VB.Net does have support for static locals, but it's accomplished by re-writing your code at compile time to move the variable to the type level (and lock the initial assignment with the Monitor class for basic thread safety).

    [post-accept addendum]
    Personally, your code sample looks meaningless to me unless you tie it to a real month. I'd do something like this:

    public static IEnumerable GetDaysInMonth(DateTime d)
    {
        d = new DateTime(d.Year, d.Month, 1);
        return Enumerable.Range(0, DateTime.DaysInMonth(d.Year, d.Month))
                 .Select(i => d.AddDays(i) );
    }
    

    Note also that I'm not using an array. Arrays should be avoided in .Net, unless you really know why you're using an array instead of something else.

提交回复
热议问题