C# 面向對象學習筆記

最近暫且不忙(Working fish),突然想學習下C#,在慕課找到了kong66老師的C#面向對象編程課程,花了3個晚上看完後受益匪淺。整理了一下筆記和代碼,以供日後查詢使用。

大綱筆記

到幕布看大圖
C# 面向對象學習筆記

代碼筆記

using System;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// C# 面向對象編程學習代碼日記
/// 學習者Blog:https://blog.csdn.net/hx7013
/// 感謝kong66老師,視頻地址:https://www.imooc.com/learn/806
/// </summary>
namespace CS_Object
{
    // 結構體
    struct fish
    {
        int weight;
        int size;
        int type;
    }

    // 接口
    interface ICatchMice
    {
        void CatchMice();
    }

    interface IClimbTree
    {
        void ClimbTree();
    }

    //基類(寵物),抽象類
    abstract public class Pet
    {
        //私有屬性習慣用 _開頭
        protected string _name;
        protected int _age;

        public Pet(string name)
        {
            _name = name;

        }

        public string GetName()
        {
            return _name;
        }

        public void PrintName()
        {
            Console.WriteLine("Pet name is: " + _name);
        }


        public void SetAge(int age)
        {
            _age = age;
        }

        public void ShowAge()
        {
            Console.WriteLine(_name + " age is: " + _age);
        }

        // virtual public void Speak() {
        //     Console.WriteLine(_name + " Speak...");
        // }

        // 抽象方法
        abstract public void Speak();

        //重載操作符
        public static Pet operator ++(Pet pet)
        {
            ++pet._age;
            return pet;
        }

    }

    //派生類(狗)
    public class Dog : Pet
    {
        //事件
        public delegate void Handler();
        public static event Handler NewDog;

        // 靜態成員
        static int Num;

        //靜態構造函數
        static Dog()
        {
            Num = 0;
        }

        //構造函數
        public Dog(string name) : base(name)
        {
            //構造時對Num++
            Num++;

            //事件
            //等效於 if(NewDog!=null){NewDog();}
            NewDog?.Invoke();
        }

        // new ,隱藏方法
        new public void PrintName()
        {
            Console.WriteLine("寵物的名字是: " + _name);
        }

        // 多態 + 密閉方法(不能再被集成修改)
        sealed override public void Speak()
        {
            base.PrintName();  //類似super().
            Console.WriteLine(_name + " Dog speak wow...");
        }

        // 靜態方法
        static public void ShowNum()
        {
            Console.WriteLine("Dog num is:" + Num);
        }

        //自定義轉換
        //隱式轉換
        public static implicit operator Cat(Dog dog)
        {
            return new Cat(dog._name);
        }

        //重載運算符
        public static Dog operator +(Dog male, Dog felmale)
        {
            return new Dog(male._name + "&" + felmale._name);
        }

        //泛型方法,約束 where
        public void IsHappy<T>(T target) where T : Pet
        {
            Console.Write("happy is: ");
            target.PrintName();
        }

        //委託
        public void WagTail()
        {
            Console.WriteLine(_name + " wag tail...");
        }
    }

    // 擴展方法
    static class PetGuide
    {
        //擴展方法,爲Dog類新增方法,注意this
        static public void HowToFreeDog(this Dog dog)
        {
            Console.WriteLine("Play a about how to feed dog...");
        }
    }

    //泛型接口抽象類
    public abstract class DogCmd
    {
        public abstract string GetCmd();
    }

    //泛型接口
    public class SitDogCmd : DogCmd
    {
        public override string GetCmd()
        {
            return "sit";
        }
    }

    //泛型接口
    public class SpeakDogCmd : DogCmd
    {
        public override string GetCmd()
        {
            return "wow....";
        }
    }
    //泛型接口
    public interface IDogLearn<C> where C : DogCmd
    {
        void Act(C cmd);
    }

    public class Labrador : Dog, IDogLearn<SitDogCmd>, IDogLearn<SpeakDogCmd>
    {
        public Labrador(string name) : base(name)
        {
        }
        //實現泛型接口
        public void Act(SitDogCmd cmd)
        {
            Console.WriteLine("Act: " + cmd.GetCmd());
        }
        //實現泛型接口
        public void Act(SpeakDogCmd cmd)
        {
            Console.WriteLine("Act: " + cmd.GetCmd());
        }
    }

    // 接口
    public class Cat : Pet, ICatchMice, IClimbTree
    {
        public Cat(string name) : base(name) { }

        //引用接口後必須實現
        public void CatchMice()
        {
            Console.WriteLine("Catch mice...");
        }

        public void ClimbTree()
        {
            Console.WriteLine("Climb Tree...");
        }

        public override void Speak()
        {
            Console.WriteLine(_name + " Cat speak miaomiao...");
        }

        //自定義類型轉換
        //顯示轉換
        public static explicit operator Dog(Cat cat)
        {
            return new Dog(cat._name);
        }

        //委託
        public void InnocentLook()
        {
            Console.WriteLine(_name + " innocent look...");
        }
    }

    /// <summary>
    /// 泛型類
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Cage<T>
    {
        //籠子
        T[] arrayCage;
        //籠子大小,readonly爲動態常量,可以延遲到構造初始化。
        readonly int _size;
        //當前數量
        int num;
        public Cage(int n)
        {
            _size = n;
            num = 0;
            arrayCage = new T[_size];
        }

        //傳入
        public void Putin(T pet)
        {
            //判斷籠子是否裝滿
            if (num < _size)
            {
                arrayCage[num++] = pet;
            }
            else
            {
                Console.WriteLine("cage is full...");
            }
        }

        //取出
        public T TakeOut()
        {
            if (num > 0)
            {
                return arrayCage[--num];
            }
            else
            {
                Console.WriteLine("cage is empty...");
                return default(T);
            }
        }
    }

    //事件
    class Client
    {
        string _clientName;

        public Client(string name)
        {
            _clientName = name;
        }

        public void WantADog()
        {
            Console.WriteLine(_clientName + " Great, I want to see the new Dog...");
        }
    }

    class Program
    {
        //委託
        delegate void ActCute();
        delegate bool StudyLambda(string str);
        static void Main(string[] args)
        {
            Console.WriteLine(">>>C# 對象基本學習<<<");
            Pet[] pets = new Pet[] { new Dog("Jack"), new Cat("Tom"), new Dog("zEr") };

            for (int i = 0; i < pets.Length; i++)
            {
                pets[i].PrintName();
                pets[i].Speak();
            }

            //接口
            PrintLog("接口");
            Cat c = new Cat("Tom2");
            IClimbTree climb = c;
            c.CatchMice(); //對象可以訪問
            climb.ClimbTree();  //接口也可以訪問

            //靜態方法及成員
            PrintLog("靜態方法及成員");
            Dog.ShowNum();

            //擴展方法
            PrintLog("擴展方法");
            Dog dog = new Dog("iTc");
            dog.HowToFreeDog();

            //代碼塊
            {
                //裝箱與拆箱操作
                PrintLog("裝箱與拆箱操作");
                int i = 3;
                object oi = i;
                oi = 10;
                i = 7;
                Console.WriteLine("i= " + i + " ,oi= " + oi.ToString());
                int j = (int)oi;
                Console.WriteLine("j= " + j);
            }

            //自定義轉換
            PrintLog("自定義轉換");

            //隱式轉換
            Dog dog2 = new Dog("iJL");
            dog2.Speak();
            Cat cat = dog2;
            cat.Speak();

            //顯示轉換
            Dog dog3 = (Dog)cat;
            dog3.Speak();

            //重載運算符
            PrintLog("重載運算符");
            Pet sonDog = dog + dog2;
            sonDog.PrintName();

            sonDog.SetAge(8);
            sonDog.ShowAge();
            sonDog++;
            sonDog.ShowAge();

            //泛型
            PrintLog("泛型");
            var dogCage = new Cage<Dog>(2);
            dogCage.Putin(dog);
            dogCage.Putin(dog2);
            dogCage.Putin(dog3);

            var dog4 = dogCage.TakeOut();
            dog4.PrintName();
            var dog5 = dogCage.TakeOut();
            dog5.PrintName();

            //泛型方法
            PrintLog("泛型方法");
            dog5.IsHappy<Cat>(cat);

            //泛型接口
            PrintLog("泛型接口");
            Labrador labrador = new Labrador("iLb");
            labrador.Act(new SitDogCmd());
            labrador.Act(new SpeakDogCmd());

            //動態數組
            PrintLog("動態數組");
            ArrayList arrayList = new ArrayList();
            arrayList.Add(new Dog("A"));
            arrayList.Add(new Dog("B"));
            for (int i = 0; i < arrayList.Count; ++i)
            {
                ((Dog)arrayList[i]).PrintName();
            }

            //列表
            PrintLog("列表");
            List<Pet> petList = new List<Pet>();
            petList.Add(new Dog("A"));
            petList.Add(new Cat("B"));
            foreach (Pet p in petList)
            {
                p.Speak();
                p.PrintName();
            }

            //字典
            PrintLog("字典");
            Pet petA = new Dog("A");
            Pet petB = new Cat("B");
            Pet petC = new Cat("C");
            Dictionary<string, Pet> petDic = new Dictionary<string, Pet>();
            petDic.Add(petA.GetName(), petA);
            petDic.Add(petB.GetName(), petB);
            Pet dicOut = null;
            dicOut = petDic["A"];
            dicOut.PrintName();

            //隊列
            PrintLog("隊列");
            Queue<Pet> queuePet = new Queue<Pet>();
            queuePet.Enqueue(petA);
            queuePet.Enqueue(petB);
            queuePet.Enqueue(petC);
            Pet queueOut = null;
            queueOut = queuePet.Dequeue();
            queueOut.PrintName();
            queueOut = queuePet.Dequeue();
            queueOut.PrintName();
            queueOut = queuePet.Dequeue();
            queueOut.PrintName();

            //棧
            PrintLog("棧");
            Stack<Pet> stackPet = new Stack<Pet>();
            stackPet.Push(petA);
            stackPet.Push(petB);
            stackPet.Push(petC);

            Pet stackOut = null;
            stackPet.Peek().PrintName();
            stackOut = stackPet.Pop();
            stackOut.PrintName();
            stackPet.Peek().PrintName();
            stackOut = stackPet.Pop();
            stackPet.Peek().PrintName();
            stackOut = stackPet.Pop();
            stackOut.PrintName();

            //委託
            PrintLog("委託");
            Dog dogD = new Dog("A");
            Cat catD = new Cat("B");
            ActCute actCute = null;
            actCute = dogD.WagTail;
            actCute += catD.InnocentLook;
            actCute();

            //匿名方法
            PrintLog("匿名方法");
            actCute = null;
            actCute = delegate ()
            {
                Console.WriteLine("這是一個匿名方法...");
            };
            actCute();

            //Lambda
            PrintLog("Lambda");
            actCute = null;
            actCute = () =>
            {
                Console.WriteLine("這是一個Lambada表達式...");
            };
            actCute();
            StudyLambda studyLambda = null;
            studyLambda = (lArgs) =>
            {
                if (lArgs == "hello")
                {
                    return true;
                }
                return false;
            };
            bool sBool = studyLambda("hello");
            Console.WriteLine("sBool is " + sBool);

            //事件
            PrintLog("事件");
            Client c1 = new Client("Hx");
            Client c2 = new Client("Wss");
            Dog.NewDog += c1.WantADog;
            Dog.NewDog += c2.WantADog;
            new Dog("HeiNiu~");

        }

        /// <summary>
        /// 打印Logs
        /// </summary>
        /// <param name="logStr">logStr</param>
        static void PrintLog(string logStr)
        {
            Console.WriteLine("\n" + logStr + "   >>>");
        }
    }
}

原帖地址:https://blog.csdn.net/hx7013/article/details/100944896
轉載請註明!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章