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

演示静态构造函数的使用
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;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值