构造函数
构造函数是在第一次创建对象时调用的方法。构造函数具有与类相同的名称,它通常用于初始化对象的数据。
不带参数的构造函数称为默认构造函数。构造函数中的代码都在创建新对象时候执行。
下面看一个默认构造函数的列子:
class Book
{
private string title;
private string author;
private double price;
public Book()
{ //默认的构造函数
title = "asp.net从入门到精通";
author = "aliang";
}
public double BookPrice
{
get { return price ;}
set { price=value*2;}
}
public string BookInfo
{
get { return "书的名称是:" + title + "<br>" + "书的作者是:" + author+"<br>"; }
}
}
protected void Page_Load(object sender, EventArgs e)
{
Book mybook = new Book();
mybook.BookPrice = 19.98;
Response.Write(mybook.BookInfo);
Response.Write("书的价格是:"+mybook.BookPrice);
}
---------------------------------------------------------------------------------------------
下面看一个带参数的构造函数的例子
class Book
{
private string title;
private string author;
private double price;
public Book(string newtitle,string newauthor)
{ //带参数的构造函数,它通常用于初始化对象的数据。
title = newtitle;
author =newauthor;
}
public double BookPrice
{
get { return price ;}
set { price=value*2;}
}
public string BookInfo
{
get { return "书的名称是:" + title + "<br>" + "书的作者是:" + author+"<br>"; }
}
}
protected void Page_Load(object sender, EventArgs e)
{
Book mybook = new Book("ASP.NET2.0从入门到精通","aliang");//注意这里,是带参数的。因为构造函数是带参数的。
mybook.BookPrice = 19.98;
Response.Write(mybook.BookInfo);
Response.Write("书的价格是:"+mybook.BookPrice);
Response.Write("<hr>");
Book mybook1 = new Book("SQL2005学习指南", "JHON");
mybook1.BookPrice = 45.88;
Response.Write(mybook1.BookInfo);
Response.Write("书的价格是:" + mybook1.BookPrice);
}