一.构造函数:
作用:帮助我们初始化对象(给对象的每个属性依次的赋值)
构造函数是一个特殊的方法:
1)、构造函数没有返回值,连void也不能写
2)、构造函数的名称必须跟类名一样
创建对象的时候会执行构造函数
构造函数是可以有重载的
类当中会有一个默认的无参数的构造函数怒,当你写了一个新的构造函数之后,不管是有参数的还是无参数的,那个默认的无参数的构造函数都被干掉了,转而代之的是新的构造函数
二.new关键字
Person zsPerson=new Person();
new帮助我们做了3件事儿:
1)、在内存中开辟一块空间
2)、在开辟的空间中创建对象
3)、调用对象的构造函数进行初始化对象
三.this关键字
1)、代表当前类的对象
2)、在类当中显示地调用本类的构造函数,调用的方式是冒号+this,即:this
定义一个学生类,有六个属性,分别为姓名、性别、年龄、语文、数学、英语成绩
一个打招呼的方法:介绍自己叫XX,今年几岁了。是男同学还是女同学。
两个计算自己总分数和平均分的方法。{显示:我叫XX,这次考试总成绩为X,平均成绩为X分}
实例化两个对象并测试:
张三 男 18 三科成绩为:90 95 80
小兰 女 16 三科成绩为:95 85 100
学生类:
Student.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace 练习题35
{
public class Student
{
//当程序结束的时候,析构函数才执行
//帮助我们释放资源
//GC Garbage Collection】
//VS2019自动回收资源,可以不写析构函数
//~Student()
//{
// Console.WriteLine("我是析构函数");
//}
public Student(string name,char gender,int age,int chinese,int math,int english)//构造函数
{
this.Name = name;
this.Gender = gender;
this.Age = age;
this.Chinese = chinese;
this.Math = math;
this.English = english;
}
//构造函数的重载
public Student(string name,int chinese,int math,int english):this(name,'c',0,chinese,math,english)//用this调用上面较全的构造函数
{
//this.Name = name;
//this.Chinese = chinese;
//this.Math = math;
//this.English = english;
}
//构造函数的重载
public Student(string name,int age,char gender)
{
//this.Name = name;
//this.Age = age;
//this.Gender = gender;
}
private string _name;
public string Name
{
set { _name = value; }
get { return _name; }
}
private char _gender;
public char Gender
{
set {
if(_gender!='男' || _gender!='女')
_gender = '男';
}
get { return _gender; }
}
private int _age;
public int Age
{
//set {
// if(_age<0||_age>200)
// {
// _age = 0;
// }
// _age = value;
// }
//get { return _age; }
set { _age = value; }
get {
if(_age<0||_age>200)
{
_age = 0;
}
return _age;
}
}
private int _chinese;
public int Chinese
{
set { _chinese = value; }
get { return _chinese; }
}
private int _math;
public int Math
{
set { _math = value; }
get { return _math; }
}
private int _english;
public int English
{
set { _english = value; }
get { return _english; }
}
public void SayHello()
{
Console.WriteLine("我叫{0},我今年{1}岁了,我是{2}生",this.Name,this.Age,this.Gender);
}
public void ShowScore()
{
Console.WriteLine("我叫{0},我的总成绩是{1},我的平均成绩是{2}",this.Name,this.Chinese+this.Math+this.English,((this.Chinese + this.Math + this.English)/3));
}
}
}
main函数:
using System;
namespace 练习题35
{
class Program
{
static void Main(string[] args)
{
//Student s = new Student("张三",100,100,100);//测试用this调用上面较全的构造函数
Student zsStudent = new Student("张三", '中', 18, 100, 100, 100);
zsStudent.SayHello();
zsStudent.ShowScore();
Student xlStudent = new Student("小兰", '女', 16, 50, 50, 50);
xlStudent.SayHello();
xlStudent.ShowScore();
Console.ReadKey();
}
}
}
