C#简单问题,高手帮帮吧,谢谢

来源:百度知道 编辑:UC知道 时间:2024/05/03 19:46:56
using System;
public class ConstructorProgram
{
private string name;
private int age;

public ConstructorProgram(): this("bell")
{
//Console.WriteLine("No Info Left.");
}
public ConstructorProgram(string name): this("Simple Programmer", 20)
{
this.name = name;
Console.WriteLine("name=" + this.name);
}
public ConstructorProgram(string name, int age)
{
this.name = name;
this.age = age;
Console.WriteLine("name=" + this.name);
Console.WriteLine("age=" + this.age);
}

public static void Main()
{
ConstructorProgram cp1 = new ConstructorProgram("goal");
ConstructorProgram cp2 = new ConstructorProgram();
Console.ReadLine();

}
}
程序中的: this(&qu

this 既当前类的指针
this("Simple Programmer", 20)

既相当于调用类 ConstructorProgram 的第三个构造函数

同理 this("bell") 调用 第二个构造函数

加上":"号写在构造函数后面,在构造当前函数之前执行,类似基类会在子类前实例化,可以以理解基类子类的方式理解,那样就很容易了

对public ConstructorProgram(string name)的调用

关键字“this”指定在调用指定的构造函数前,.NET实例化过程对当前类使用非默认的构造函数。具体分析如下:
ConstructorProgram cp1 = new ConstructorProgram("goal");
执行序列如下:
1.调用public ConstructorProgram(string name, int age)函数,输出
name=Simple Programmer
age=20;
2.再调用public ConstructorProgram(string name): this("Simple Programmer", 20) ,输出
name=goal
ConstructorProgram cp2 = new ConstructorProgram();
执行序列如下:
1.调用public ConstructorProgram(string name, int age)函数,输出
name=Simple Programmer
age=20;
2.再调用public ConstructorProgram(string name): this("Simple Programmer", 20) ,输出
name=bell
3.最后调用public ConstructorProgram()。你把输出语句注释了,无输出。
综上,你的程序输出为: