重载构造函数+复用构造函数+原始构造与This引用的区别(一步步案例分析)

先说原始的构造函数:

案例1:<类的重载构造函数>

class Program
{
static void Main(string[] args)
{
Person oneperson1 = new Person(15,"jack",160.00);//调用第一个构造函数

Console.WriteLine(oneperson1);//这里隐式ToString()方法
Person oneperson2 = new Person("jack", 15,160.00);//调用第二个构造函数
Console.WriteLine(oneperson2);

Person oneperson3 = new Person();//默认是隐式有一个不带参数的构造函数,但是如果自定义构造函数,不加参数会报错,所以要显式一个无参数构造函数
Console.WriteLine(oneperson3);
}
}


class Person
{
private int age;//这里只是声明,没有初始化实例,所以程序运行的时候不会经过这一步,直接进入构造函数
private string name;
private double height;

public Person()//不包含参数的构造函数
{
Console.WriteLine("The None !");
}
public Person(int him_age,string him_name,double him_height)
{
age = him_age;
name = him_name;
height = him_height;
Console.WriteLine("The First constructor !");
}


public Person(string him_name, int him_age, double him_height)
{
age = him_age;
name = him_name;
height = him_height;
Console.WriteLine("The Second constructor !");
}

public override string ToString()//对于对象的ToString方法必须重写
{
return string.Format(age+""+name+""+height); ;
}

}
/*
The Result:

The First constructor !
15 jack 160
The Second constructor !
15 jack 160
The None !
0 0 //注意:0 与 0 之间有一个Empty是string name
*/




This 引用:
案例2:
 

class Program
{
static void Main(string[] args)
{
Time timetest = new Time();
D(timetest);

Time timetest1 = new Time(10, 10, 10);
D(timetest1);

Time timetest2 = new Time(20,20);
D(timetest2);

Time timetest3 = new Time(timetest2);//调用对象作为构造函数的参数
D(timetest3);
}

static void D<T>(T timetest)//不想写Console.Writeline();这么长的代码
{
Console.WriteLine(timetest);
}
}


class Time
{
private int hour;
private int min;
private int second;

//5个构造函数
public Time() : this(0,0,0) { }//this 复用构造函数初始器,原本0个参数值直接是默认的0

public Time(int h) : this(h, 0, 0) { }//这里传入1个值,原则是是 到Get属性,但是这里复用了另一个构造函数(3个变量的构造函数)

public Time(int h, int m) : this(h, m, 0) { }

public Time(int h, int m, int s)
{
Settime(h,m,s);
}

public Time(Time timetest) : this(timetest.Hour,timetest.Min,timetest.Second) { }//对象作为构造函数的参数
//1.这里是先读取timetest的值
//2.再根据构造函数赋值(复用构造函数)


public void Settime(int h, int m, int s)
{
Hour = h;
Min = m;
Second = s;
}


//属性
public int Hour//属性是没有参数的
{
get { return hour; }
private set { hour = value; }//这么写为了只能在构造函数里给初始化实例
}


public int Min
{
get { return min; }
private set { min = value; }
}

public int Second
{
get { return second; }
private set { second = value; }
}


public override string ToString()//重写ToString方法
{
return string.Format("hour :{0} min :{1} second : {2}", hour, min, second); ;
}
}
/*
The Result:
hour :0 min :0 second : 0
hour :10 min :10 second : 10
hour :20 min :20 second : 0
hour :20 min :20 second : 0
*/



posted @ 2011-12-19 16:04  Anleb  阅读(2365)  评论(3编辑  收藏  举报