构造函数和析构函数(1)

共性:编写代码时,如果没有提供他们,则编译自动添加

作用:帮助我们初始化对象(给对象的每个属性依次的赋值)

构造函数时一个特殊的方法:

构造函数没有返回值,连void也不能写。必须public

构造函数的名称必须和类名一样

创建步骤:

1.新建一个带main函数的类 

2.新建类clerk,快速新建类文件的方法:AIT+Shft+C

代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _9._8_构造函数和析构函数
{
public enum Gender
{
男,

}
class clerk
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
//自动生成属性的快捷方式 ,先手写private Gender _Gender; 再执行Ctrl+r+e

private Gender _Gender;
public Gender Gender
{
get { return _Gender; }
set { _Gender = value; }
}
private int _Age;
//年龄
public int Age
{
get { return _Age; }
set { _Age = value; }
}
private string _departent;
//部门方法
public string Departent
{
get { return _departent; }
set { _departent = value; }
}
public void Write()
{
Console.WriteLine("我叫{0},我今年{1}岁了,我现在在{2}工作", this.Name, this.Age, this.Departent);
}
//构造函数的方法,必须public类型,加当前类名
public clerk(string name, Gender gender, int age, string departent)
{
this.Name = name;
this.Gender = gender;
this.Age = age;
this.Departent = departent;
}
}
}

带main函数的代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _9._8_构造函数和析构函数
{
class Program
{
static void Main(string[] args)
{
//不使用构造函数进行赋值
/*
clerk wj = new clerk();
wj.Name = "锦大大";
wj.Gender = Gender.男;
wj.Age = 22;
wj.Departent = "开发部";
wj.Write();
Console.ReadKey();
*/
//使用构造函数进行赋值
clerk wj = new clerk("锦大大",Gender.男,22,"软件部");
wj.Write();
Console.ReadKey();
}
}
}

猜你喜欢

转载自www.cnblogs.com/wangjinya/p/9672049.html