深刻理解構造函數和屬性

記得剛學構造函數和屬性的時候,一直感受這些東西沒什麼用,好比屬性,明明我用字段就能夠實現了,幹嗎還要多寫那幾行代碼,後來作的項目多了,看的書也多了,才慢慢體會到不少編程語言高級特性的妙處,才真正理解了這些特性的本質,好比 C#中委託實際上就至關於C語言的函數指針,經過委託把函數當參數來提升程序的靈活性和低耦合性。這裏經過一個簡單的實例來寫一下本身的一些理解,註釋裏寫的很詳細了,話就很少說了。編程

Human類:

class Human
    {
        //經過有參數的構造函數進行初始化   構造函數能夠重載
        public Human(string name, int age, bool isgirl, string country)
        {
            Console.WriteLine("這是第一個構造函數:");

            Name = name;
            Age = age;
            IsGirl = isgirl;
            Country = country;
            SayHi();            
        }

        public Human(string name, int age, string country)
        {
            Console.WriteLine("這是第二個構造函數:");

            Name = name;
            Age = age;            
            Country = country;
        }

        //經過定義屬性 使得其餘類不能直接修改這個類裏的字段 從而實現更好的封裝
        //簡潔法 定義屬性和字段 字段編譯器自動生成的
        public string Name { get; set; }
        public int Age { get; set; }
        public bool IsGirl { get; set; }
        public string Country { get; set; }

        //下面是通常方法定義字段和屬性
        //private string name;
        //public string Name
        //{
        //    get { return name; }
        //    set { name = value; }
        //}

        //打招呼方法
        public void SayHi()
        {
            Console.WriteLine("你好,我叫{0},我{1}歲了,我是個{2}生,我來自{3}", Name, Age, (IsGirl ?"女生":"男"),Country );  //這裏用到了三元運算符  若是是 就:前面的 否 就:後面的
        }

    }

Program類

class Program
    {
        //這個練習是對屬性和構造函數的綜合應用
        static void Main(string[] args)
        {
            //直接用構造函數初始化就執行了全部操做  相對一個一個賦值再調用方法簡潔不少
            Human xiaoming = new Human("小明",19,false,"中國");

            //這個是構造函數的重載  用於實現不一樣的初始化 或者說 功能
            //Human xiaoming = new Human("小明", 19, "中國");   

            Console.ReadKey();
        }
    }

程序運行結果

這是第一個構造函數:
你好,我叫小明,我19歲了,我是個男生,我來自中國
相關文章
相關標籤/搜索