为什么这不起作用?
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,20,21,22,23,24,25,26,27,28,29,30,31};
return MonthDays;
}
Run Code Online (Sandbox Code Playgroud)
我不得不在方法之外移动变量声明:
static int[] MonthDays = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
public static int[] GetListOfAllDaysForMonths()
{
return MonthDays;
}
Run Code Online (Sandbox Code Playgroud)
另外,通过这种方式创建它,我们只有一个这个数组的实例在内存中浮动?此方法位于静态类中.
Joe*_*orn 17
C#根本不支持静态本地.静态的任何东西都需要是类型或类型本身的成员(即静态类).
顺便说一句,VB.Net确实支持静态本地,但它是通过在编译时重写代码将变量移动到类型级别(并使用Monitor类锁定初始赋值以实现基本线程安全性)来实现的.
[post-accept addendum]就
个人而言,你的代码示例对我来说毫无意义,除非你把它绑在一个真实的月份.我会做这样的事情:
public static IEnumerable<DateTime> 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) );
}
Run Code Online (Sandbox Code Playgroud)
另请注意,我没有使用数组. 在.Net中应该避免使用数组,除非你真的知道为什么要使用数组而不是其他东西.
您只能在类/ struct范围中创建静态变量.它们是静态的,这意味着它们是在类型(而不是方法)上定义的.
这就是C#使用术语"静态"的方式,这与在某些其他语言中使用"静态"的方式不同.
| 归档时间: |
|
| 查看次数: |
1220 次 |
| 最近记录: |