C#源代码—演示静态构造函数的使用

来源:互联网 发布:害怕别人超过自己知乎 编辑:程序博客网 时间:2024/05/16 01:05
演示静态构造函数的使用
using System;class Test{    public int x;      static public int y;    //实例构造函数,初始化字段x    public Test(int x)    {        this.x = x;    }    //静态构造函数,初始化静态字段y    static Test()    {        y = 1;    }}class TestStatic{    static void Main()    {              //调用实例构造函数创建对象,静态构造函数将自动被调用        Test t = new Test(1);       //字段x和y都将被初始化        Console.WriteLine("{0},{1}",t.x,Test.y);        //修改字段的值        t.x++;        Test.y++;         Console.WriteLine("{0},{1}", t.x, Test.y);        //调用实例构造函数重新创建对象,但静态构造函数不会被调用        t = new Test(0);       //只有字段x被初始化        Console.WriteLine("{0},{1}", t.x, Test.y);    }}

派生类的构造函数
例如,如果基类Person的构造函数为:
 public Person(string name, char sex)    {        Name = name;        Sex = sex;    }


则其派生类的构造函数就可写成:

public Student(string name, char sex, string school, int score)        : base(name, sex)    {        School = school;        Score = score;    }


0 0
原创粉丝点击