摘要
构造函数的名字是与类的名称相同的,在创建类对象时执行的。
析构函数则是在垃圾回收、释放资源时使用的。
正文
构造函数
类中的一种特殊的方法
构造函数名与类名相同,不返回任何值
可初始化成员变量
public class Material
{
///
/// 无参数构造函数
///
public Material()
{
}
///
/// 无参数构造函数
///
public Material(string name, int qty, string location)
{
this.name = name;
this.qty = qty;
this.location = location;
}
private string name;//字段
//定义了一个Qty的属性
private int _qty = 0;
public int qty
{
get
{
return _qty;
}
set
{
if(value<0 || value > 100)
{
throw new ArgumentException("数据不在范围内!");
}
_qty = value;
}
}
//简单定义
public string location { get; set; }
public void Print()
{
Console.WriteLine(#34;{this.name},{this.qty},{this.location}");
}
}调用
static void Main(string[] args)
{
Material material = new Material("A--1", 100, "SH01");
material.Print();
}私有构造函数
public class Material
{
///
/// 做了一个私有的构造
///
private Material()
{
}
///
/// 通过这种模式创建类
///
///
public static Material Instance()
{
return new Material();
}
private string name;//字段
//定义了一个Qty的属性
private int _qty = 0;
public int qty
{
get
{
return _qty;
}
set
{
if(value<0 || value > 100)
{
throw new ArgumentException("数据不在范围内!");
}
_qty = value;
}
}
//简单定义
public string location { get; set; }
public void Print()
{
Console.WriteLine(#34;{this.name},{this.qty},{this.location}");
}
}调用
static void Main(string[] args)
{
Material material = Material.Instance();//通过静方法创建类
material.Print();
}这种方式未来我们会讲到单例应用时会细说。
静态构造函数
用途
public class Material
{
static DateTime create_date;
///
/// 静态构造函数
///
static Material()
{
create_date = DateTime.Now;
}
private string name;//字段
//定义了一个Qty的属性
private int _qty = 0;
public int qty
{
get
{
return _qty;
}
set
{
if(value<0 || value > 100)
{
throw new ArgumentException("数据不在范围内!");
}
_qty = value;
}
}
//简单定义
public string location { get; set; }
public void Print()
{
Console.WriteLine(#34;{this.name},{this.qty},{this.location},{create_date}");
}
}调用
static void Main(string[] args)
{
Material material =new Material();
material.Print();
}终结器(以前称为析构函数)用于在垃圾回收器收集类实例时执行任何必要的最终清理操作。
public class Material
{
public Material()
{
}
~Material()
{
Console.WriteLine("终结器");
}
}| 留言与评论(共有 0 条评论) “” |