构造函数的作用
帮助我们初始化对象,即给每个对象属性赋值
构造函数是什么
1.构造函数是一个特殊的方法,没有返回值,连void也不能写。
2.构造函数的名称必须和类名一样。
3.构造函数必须是public的
原因:创建对象时使用new 来创建,它会给我们做三件事情。
1)在内存中开辟块空间
2)在开辟的空间中创建对象
3)调用对象的构造函数初始化对象。
4. 不写构造函数的话会默认有一个无参数的构造函数。写上后这个默认的就消失了。
5. 构造函数可以进行重载。重载就是方法名相同,参数不同。
例子
没有构造函数
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02构造函数
{
class Student
{
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private int _age;
public int Age
{
get { return this._age; }
set { this._age = value; }
}
private char _gender;
public char Gender
{
get { return this._gender; }
set { this._gender = value; }
}
private double _score;
public double Score
{
get { return this._score; }
set { this._score = value; }
}
public void Introduce()
{
Console.WriteLine("我叫{0},我是{1}生,我今年{2}岁了,我的分数是{3}分",this.Name,this.Gender,this.Age,this.Score);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02构造函数
{
class Program
{
static void Main(string[] args)
{
Student zsStudent = new Student();
zsStudent.Name = "张三";
zsStudent.Age = 18;
zsStudent.Gender = '男';
zsStudent.Score = 100;
zsStudent.Introduce();
Student lsStudent = new Student();
lsStudent.Name = "李斯";
lsStudent.Age = 18;
lsStudent.Gender = '女';
lsStudent.Score = 80;
lsStudent.Introduce();
Console.ReadKey();
}
}
}
没有构造函数的,初始化对象要对属性一个一个手动赋值。
有构造函数的
Student.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02构造函数
{
class Student
{
//构造函数
public Student(string name,int age,char gender,double score)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
this.Score = score;
}
public Student(string name, int age, char gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
private string _name;
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private int _age;
public int Age
{
get { return this._age; }
set { this._age = value; }
}
private char _gender;
public char Gender
{
get { return this._gender; }
set { this._gender = value; }
}
private double _score;
public double Score
{
get { return this._score; }
set { this._score = value; }
}
public void Introduce()
{
Console.WriteLine("我叫{0},我是{1}生,我今年{2}岁了,我的分数是{3}分",this.Name,this.Gender,this.Age,this.Score);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _02构造函数
{
class Program
{
static void Main(string[] args)
{
Student zsStudent = new Student("张三",18,'男',100);
//zsStudent.Name = "张三";
//zsStudent.Age = 18;
//zsStudent.Gender = '男';
//zsStudent.Score = 100;
zsStudent.Introduce();
Student lsStudent = new Student("李斯",20,'女');
//lsStudent.Name = "李斯";
//lsStudent.Age = 18;
//lsStudent.Gender = '女';
//lsStudent.Score = 80;
lsStudent.Introduce();
Console.ReadKey();
}
}
}