C# 面向对象4 构造函数
构造函数
1.构造函数用来创建对象,并且可以在构造函数中对对象进行初始化.
(给对象的每个属性依次的赋值)
2.构造函数是用来创建对象的特殊方法:
1.方法名和类名一样.
2.没有返回值,连void都不用..
**创建对象的时候会执行构造函数.(静态类呢?静态类不创建对象)
3.new 关键字
Person zs = new Person();
new帮助我们做了3件事儿:
1.在内存中开辟了一块空间
2.在开辟的空间中创建对象
3.调用对象的构造函数进行初始化
**所以构造函数必须是Public!
**构造函数可以有参数,new对象的时候传递函数参数即可.
4.构造函数可以重载,也就是有多个参数不同的构造函数.
**如果不指定构造函数,则类有一个默认的无参构造函数;
**如果指定了构造函数,则不再有默认的无参构造函数;
**如果类中已经有指定参数的构造函数,如果需要无参构造函数,则需要自己来写.
**构造函数的最大优点是,可以方便快捷的对对象初始化!!!
类代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04面向对象练习 { public class Student { //字段,属性,方法,构造函数 //构造函数 public Student(string name,int age,char gender,int chinese,int math,int english) { // this.Name = name; this.Age = age; this.Gender = gender; this.Chinese = chinese; this.Math = math; this.English = english; } public Student(string name) { this.Name = name; } public Student() { Console.WriteLine("Hello!"); } private string _name; public string Name { get { return _name; } set { _name = value; } } private int _age; public int Age { get { return _age; } set { if (value < 0 || value > 100) value = 0; _age = value; } } private char _gender; public char Gender { get { if(_gender !='男'&&_gender!='女') return _gender='男'; return _gender; } set { _gender = value; } } private int _chinese; public int Chinese { get { return _chinese; } set { _chinese = value; } } private int _math; public int Math { get { return _math; } set { _math = value; } } private int _english; public int English { get { return _english; } set { _english = value; } } 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; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _04面向对象练习 { class Program { static void Main(string[] args) { Student a = new Student("zq", 31, '中', 100, 100, 100); //a.Name = "zq"; //a.Age = 31; //a.Gender = '男'; //a.Chinese = 90; //a.English = 89; //a.Math = 99; a.SayHello(); a.ShowScore(); Student b = new Student("junfeng",34,'女',50,50,50); //b.Name = "junfeng"; //b.Age = 34; //b.Gender = '女'; //b.Chinese = 61; //b.Math = 90; //b.English = 100; b.SayHello(); b.ShowScore(); Console.ReadKey(); } } }
You are never too old to set another goal or to dream a new dream!!!