一点疑问:关于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 怀沙 阅读(968) 评论(4)  编辑 收藏

  回复  引用  查看    
#1楼 2004-08-17 16:10 | 吕震宇      
没错,C#编译器会自动添加一些细节在里面。因为c和d都是Test的成员,系统会自动添加"Test."在前面。而且静态数据不一定非在静态构造函数中初始化。(面向对象的基础还没有砸牢) :-)
  回复  引用    
#2楼 2004-09-04 17:07 | test [未注册用户]
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);
    }


}

  回复  引用  查看    
#4楼 [楼主]2005-08-06 21:25 | 怀沙      
一年以后再回头来看这个问题,想不通自己当时为什么不理解
不过这正说明自己在不停地进步中:)


标题  
姓名  
主页
Email (只有博主才能看到) 
验证码 *  看不清,换一张 [登录][注册]
内容(请不要发表任何与政治相关的内容)  
  登录  使用高级评论  新用户注册  返回页首  恢复上次提交      
该文被作者在 2005-07-20 23:30 编辑过


相关链接: