溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

39.C#--面對(duì)對(duì)象構(gòu)造函數(shù)及構(gòu)造函數(shù)繼承使用

發(fā)布時(shí)間:2020-08-16 07:45:23 來(lái)源:網(wǎng)絡(luò) 閱讀:212 作者:初禾 欄目:編程語(yǔ)言

//一.新建Person類
namespace _39.面對(duì)對(duì)象構(gòu)造函數(shù)及構(gòu)造函數(shù)繼承使用
{
public class Person
{
//字段、屬性、方法、構(gòu)造函數(shù)
//字段:存儲(chǔ)數(shù)據(jù)
//屬性:保護(hù)字段,對(duì)字段的取值和設(shè)值進(jìn)行限定
//方法:描述對(duì)象的行為
//構(gòu)造函數(shù):初始化對(duì)象(給對(duì)象的每個(gè)屬性依次的賦值)
//類中的成員,如果不加訪問(wèn)修飾符,默認(rèn)都是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)  //對(duì)年齡賦值進(jìn)行設(shè)定,
            {                              //小于0或大于100都默認(rèn)取0

value = 0;
}
_age = value; }
}

    public char _gender;       //字段
    public char Gender             //屬性
    {
        get { return _gender; }
        set { if(value!='男' || value != '女')  //對(duì)賦值進(jìn)行限定
            {                                 // 如果輸入不是男或女的,默認(rèn)都取男
                value = '男';
            }
            _gender = value; }
    }

    public int _id;      //字段
    public int Id       //屬性
    {
        get { return _id; }
        set { _id = value; }
    }
    //構(gòu)造函數(shù):1、沒(méi)有返回值 連void也沒(méi)有
    //2、構(gòu)造函數(shù)的名稱跟類名一樣
    public Person(string name,int age,char gender,int id)  //構(gòu)造函數(shù),main函數(shù)傳參過(guò)來(lái)
    {   //this:當(dāng)前類的對(duì)象
        //this:調(diào)用當(dāng)前類的構(gòu)造函數(shù)
        this.Name = name;            //this.Name指這個(gè)類中的屬性值,將main函數(shù)傳過(guò)來(lái)的值賦給屬性值
        this.Age = age;             //同上
        this.Gender = gender;
        this.Id = id;
    }
    public Person(string name,char gender) : this(name,0,gender,0) { }  //繼承上面那個(gè)構(gòu)造函數(shù)
    public void SayHellOne()     //方法一
    {
        Console.Write("我是{0},我今年{1}歲了,我是{2}生,我的學(xué)號(hào)是{3}", this.Name, this.Age, this.Gender, this.Id);
    }
    public static void SayHelloTwo()   //方法二, 靜態(tài)函數(shù)只能夠訪問(wèn)靜態(tài)成員
    {
        Console.WriteLine("我是靜態(tài)的方法!");
    }
            public Person()
    {

    }
}

}

二:main函數(shù)調(diào)用
namespace _39.面對(duì)對(duì)象構(gòu)造函數(shù)及構(gòu)造函數(shù)繼承使用
{
class Program
{
static void Main(string[] args)
{
//39.面對(duì)對(duì)象構(gòu)造函數(shù)及構(gòu)造函數(shù)繼承使用
Person lsPerson = new Person("張三",18,'男',100); //新建對(duì)象,調(diào)用構(gòu)造一方法
lsPerson.SayHellOne();
Console.WriteLine(); //換行
Person xlPerson = new Person("小蘭", '女'); //新建對(duì)象,調(diào)用構(gòu)造二方法
xlPerson.SayHellOne();
Console.WriteLine(); //換行
Person.SayHelloTwo(); //調(diào)用靜態(tài)方法
Console.ReadKey();
}
}
}

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI