您的位置:首页 > 编程语言 > C#

总结:C#语法系列——构造函数

2010-10-27 21:10 323 查看
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class parent
{
public static string str = "parent类的static静态字段";

//静态构造函数前不能有访问限制符。
//在 类被实例化、访问类的静态成员 时会自动调用静态构造函数,并且只调用 1次!
static parent()
{
Console.WriteLine("0.父类parent的无参数static构造函数");
}

public static void Fun()
{
Console.WriteLine("父类parent的Fun静态方法");
}

public parent()
{
Console.WriteLine("1.父类parent的无参数构造函数");
}

public parent(int I)
{
Console.WriteLine("2.父类parent的(int I)参数构造函数");
}

//若父类中有带参数的构造函数,系统不会生成不带参数的构造函数,此时系统会报错
//若父类中没有带参数的构造函数,系统会生成不带参数的构造函数,此时系统不会报错

//以后书写最好的方法:父类中都要书写一个无参数的构造函数,不管无参构造函数中有没有操作
}

class son : parent
{
public son()
{
Console.WriteLine("3.子类son的无参数构造函数");
}

public son(int a)
{
Console.WriteLine("4.子类son的(int a)参数构造函数");
}

//自动先调用冒号后面的构造函数。在这里this(i)是son类的public son(int a)
public son(string str, int i) : this(i)
{
Console.WriteLine("5.子类son的(string str, int i) : this(i)参数构造函数");
}

//自动先调用冒号后面的构造函数。在这里base(i)是parent类的public parent(int I)
public son(string str, string str2, int i) : base(i)
{
Console.WriteLine("6.子类son的(string str, string str2, int i) : base(i)构造函数");
}
}

class construct
{
static void Main()
{
Console.WriteLine(parent.str);
parent.Fun();
Console.WriteLine();

son son1 = new son(8);
Console.WriteLine();

son son2 = new son("dd", 8);//先调用父类的构造函数,在调用子类的构造函数
Console.WriteLine();

son son3 = new son("dd", "ff", 8);
Console.ReadLine();
}
//还有一种通过 tprivate修饰的私有构造函数 的类,其特点是限制了类不能被实例化,类中都是static静态的成员。
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: