39.C#--面对对象构造函数及构造函数继承使用

2023-06-28,,

//一.新建Person类
namespace _39.面对对象构造函数及构造函数继承使用
{
public class Person
{
//字段、属性、方法、构造函数
//字段:存储数据
//属性:保护字段,对字段的取值和设值进行限定
//方法:描述对象的行为
//构造函数:初始化对象(给对象的每个属性依次的赋值)
//类中的成员,如果不加访问修饰符,默认都是private
private string _name; //字段
public string Name //属性
{
get { return _name; }
set { _name = value; }
}

    public int _age;  //字段
    public int Age     //属性
    {
        get { return _age; }
        set {if(value<=0 || value >= 100)  //对年龄赋值进行设定,
            {                              //小于0或大于100都默认取0

value = 0;
}
_age = value; }
}

    public char _gender;       //字段
    public char Gender             //属性
    {
        get { return _gender; }
        set { if(value!='男' || value != '女')  //对赋值进行限定
            {                                 // 如果输入不是男或女的,默认都取男
                value = '男';
            }
            _gender = value; }
    }

    public int _id;      //字段
    public int Id       //属性
    {
        get { return _id; }
        set { _id = value; }
    }
    //构造函数:1、没有返回值 连void也没有
    //2、构造函数的名称跟类名一样
    public Person(string name,int age,char gender,int id)  //构造函数,main函数传参过来
    {   //this:当前类的对象
        //this:调用当前类的构造函数
        this.Name = name;            //this.Name指这个类中的属性值,将main函数传过来的值赋给属性值
        this.Age = age;             //同上
        this.Gender = gender;
        this.Id = id;
    }
    public Person(string name,char gender) : this(name,0,gender,0) { }  //继承上面那个构造函数
    public void SayHellOne()     //方法一
    {
        Console.Write("我是{0},我今年{1}岁了,我是{2}生,我的学号是{3}", this.Name, this.Age, this.Gender, this.Id);
    }
    public static void SayHelloTwo()   //方法二, 静态函数只能够访问静态成员
    {
        Console.WriteLine("我是静态的方法!");
    }
            public Person()
    {

    }
}

}

二:main函数调用
namespace _39.面对对象构造函数及构造函数继承使用
{
class Program
{
static void Main(string[] args)
{
//39.面对对象构造函数及构造函数继承使用
Person lsPerson = new Person("张三",18,'男',100); //新建对象,调用构造一方法
lsPerson.SayHellOne();
Console.WriteLine(); //换行
Person xlPerson = new Person("小兰", '女'); //新建对象,调用构造二方法
xlPerson.SayHellOne();
Console.WriteLine(); //换行
Person.SayHelloTwo(); //调用静态方法
Console.ReadKey();
}
}
}

《39.C#--面对对象构造函数及构造函数继承使用.doc》

下载本文的Word格式文档,以方便收藏与打印。