C#构造函数使用

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

构造函数是一个特殊的方法

1、构造函数没有返回值,连void也不能写

2、构造函数名称要和类名一样

3、创建对像时会执行构造函数

4、构造函数可以重载

类中默认有一个构造函数(隐藏的),如果你创建了一个构造函数,不管是有参数的,还是无参数的,他默认的那个无参数的构造函数都会消失,如果你需要无参的就要重新自已写

students 类

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

namespace ClassLibrary1
{
    public class Students
    {
        //创建对像时使用
        public Students(string name, int age, char gender, int englist, int chinese, int math)
        {
            this.Name = name;
            this.Age = age;
            this.Gender = gender;
            this.Englist = englist;
            this.Chinese = chinese;
            this.Math = Math;
        }
        public Students(string name, int age)
        {
            this.Name = name;
            this.Age = age;
        }

        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 != '女')
                {
                _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 Englist
        {
            get { return _english; }
            set { _english = value; }
        }
        public void SayHello()
        {
            Console.WriteLine("我叫{0},我是{1}性,我今年{2}岁", this.Name, this.Gender, this.Age);
        }
        public void ShowScore()
        {
            Console.WriteLine("我叫{0},我的总成绩是{1},我的平均成绩是{2}", this.Name, this.Chinese + this.Math + this.Englist, (this.Chinese + this.Math + this.Englist) / 3);
        }
    }
}

program 类

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

namespace ClassLibrary1
{
    public static class Program
    {
        
        public static void Main(string[] args)
        {
            
           Students zs=new Students("张三", 21, '男', 90, 22, 44);
           zs.SayHello();
           zs.ShowScore();
           Students ls=new Students("李四", 28, '女', 80, 52, 43);
           ls.SayHello();
           ls.ShowScore(); ;
            Console.ReadKey();
        }

    }
}