一点疑问:关于static 和static readonly

先看一个程序:

using System;

class Test
{
    
public const int a=100;
    
public readonly int b;
    
public static readonly int c=300;

    Test()
    
{
        b
=200;
        
//c=300;  错误:不能在构造函数里被赋值
    }


    
public static void Main()
    
{
        Test e
=new Test ();
    
        Console.WriteLine (
"{0},{1},{2}",a,e.b ,c);
    }



}

一个字段被声明为static readonly,则不可以在构造函数里被赋值

我的理解是一个字段被声明为静态的(static),则它只能实类名而不是对象名来访问
构造函数是在实例化一个类的时候被调用,而对于静态的字段,放在构造函数里是没有意义的.
解决办法是把它放在静态构造函数中.

static Test()
{
    c
=200;
}

再看一个程序:

using System;

class Test
{
    
    
public static readonly int c=300;
       
public static int d=0;
    
    Test()
    
{
    
        d
=400;
    }


    
static Test()
    
{
        c
=300;
    }


    
public static void Main()
    
{

        Console.WriteLine (
"{0},{1}",c,d);
    }



}

此程序编译通过...
输出结果为 300,0

若改成

public static void Main()
    
{
        Test e
=new Test ();
        Console.WriteLine (
"{0},{1}",c,d);
    }

则输出结果为 300,400

d被声明为静态,却不必放在静态构造函数中..?

posted @ 2004-08-17 14:23  怀沙  阅读(1254)  评论(4编辑  收藏  举报