先看一个程序:
using System;
![](/Images/OutliningIndicators/None.gif)
class Test
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
public const int a=100;
public readonly int b;
public static readonly int c=300;
![](/Images/OutliningIndicators/InBlock.gif)
Test()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
b=200;
//c=300; 错误:不能在构造函数里被赋值
}
![](/Images/OutliningIndicators/InBlock.gif)
public static void Main()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Test e=new Test ();
Console.WriteLine ("{0},{1},{2}",a,e.b ,c);
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
}
![](/Images/OutliningIndicators/None.gif)
一个字段被声明为static readonly,则不可以在构造函数里被赋值
我的理解是一个字段被声明为静态的(static),则它只能实类名而不是对象名来访问
构造函数是在实例化一个类的时候被调用,而对于静态的字段,放在构造函数里是没有意义的.
解决办法是把它放在静态构造函数中.
再看一个程序:
using System;
![](/Images/OutliningIndicators/None.gif)
class Test
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/ContractedBlock.gif)
{
public static readonly int c=300;
public static int d=0;
Test()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
d=400;
}
![](/Images/OutliningIndicators/InBlock.gif)
static Test()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
c=300;
}
![](/Images/OutliningIndicators/InBlock.gif)
public static void Main()
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine ("{0},{1}",c,d);
}
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
}
![](/Images/OutliningIndicators/None.gif)
此程序编译通过...
输出结果为 300,0
若改成
public static void Main()
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
Test e=new Test ();
Console.WriteLine ("{0},{1}",c,d);
}
则输出结果为 300,400
d被声明为静态,却不必放在静态构造函数中..?