目录
相关知识点
构造函数:初始化对象
析构函数:清理对象
定义类时可以不定义相关的构造函数和析构函数。
System.Object提供了一个默认的实现方式。
构造函数的格式
默认构造函数格式:
class MyClass{
public MyClass(){
初始化代码
}
}
非默认构造函数格式:
class MyClass{
public MyClass(int myInt){
初始化代码
}
}
零碎知识点
每一个类都需要一个构造函数
如果没提供构造函数,编译器会自动创建一个构造函数。
如果仅提供一个非默认构造函数,则禁止使用new MyClass()
构造函数数量没有限制
派生类成员:父类继承+子类扩充
基类中的私有成员不可以直接访问,派生类不可以直接访问基类中的私有成员。
允许构造函数之间相互调用。
可以用base关键字指定调用基类的构造函数。
可以用this关键字指定调用当前类的构造函数
构造函数的调用规则:
先调用基类的构造函数,再调用当前类的构造函数。
代码练习
基类TV,派生类SmartTV
TV.cs
using System;
namespace TV
{
class TV
{
private double _price;
public double Price{
set {
if( value<1000){
_price=1000;
}
else
_price=value;
}
get{
return _price;
}
}
public TV(){
_price=0;
Console.WriteLine("默认构造TV");
}
public TV(double price){
_price=price;
Console.WriteLine("默认构造TV");
}
}
}
SmartTV.cs
using System;
namespace TV
{
class SmartTV : TV
{
public string Brand { set; get; }
public string SmartLevel { set; get; }
public SmartTV()
{
Brand = "不出名";
Console.WriteLine("默认构造 SmartTV");
}
public SmartTV(string brand, double price)
{
Brand = brand;
Console.WriteLine("用brand和price构造 SmartTV");
}
//允许构造函数之间相互调用
public SmartTV(string brand, double price, string smartLevel) : this(brand, price)
{
//Brand=brand;
SmartLevel = smartLevel;
Console.WriteLine("用brand、price和SmartLevel构造 SmartTV");
}
}
}
Program.cs
using System;
namespace TV
{
class Program
{
static void Main(string[] argc){
SmartTV myTV=new SmartTV("海尔电视",2000,"很智能");
}
}
}
运行结果:
欢迎点赞、关注、收藏~