星期二, 1月 24, 2017

[C#] new 關鍵字

閱讀該 [線上讀書會] 繼承 (Inheritance) new、virtual、override、abstract 影片筆記,主要是紀錄 new 的使用方式

[C#] new 關鍵字-1
Employ class
namespace ConsoleApplication1
{
    public class Employee
    {
        public string Name { get; set; }
        public decimal Salary { get; set; }

        // virtual 和 overirde 關鍵字說明使用
        public virtual void overrideShow()
        {
            Console.WriteLine($"{Name} 薪資為 {Salary}");
        }
  
        // new 關鍵字說明使用
        public void NewShow()
        {
            Console.WriteLine($"{Name} => Employee.NewShow()");
        }
    }
}

Manager class
namespace ConsoleApplication1
{
    public class Manager : Employee
    {
        public decimal Bonus = 5000;

        public override void overrideShow()
        {
            // 利用 base 關鍵字呼叫 Employee.overrideShow()
            base.overrideShow();
            // override 後的 Manager 內容
            Console.WriteLine($"{Name} 薪資為 {Salary} + 獎金 {Bonus} = {Salary + Bonus}");
        }

        public new void NewShow()
        {
            Console.WriteLine($"{Name} => Manager.NewShow()");
        }
    }
}
Program.cs
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("====== Virtual、Override 關鍵字說明 =====");

            Employee e1 = new Manager();
            e1.Name = "管理人員";
            e1.Salary = 50000;
            e1.overrideShow();

            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");
            Console.WriteLine("");

            Console.WriteLine("===== New 關鍵字說明 =====");

            Employee e2 = new Employee();
            e2.Name = "Employee e2 = new Employee()";
            e2.NewShow();

            Console.WriteLine("----------");

            Manager m2 = new Manager();
            m2.Name = "Manager m2 = new Manager()";
            m2.NewShow();

            Console.WriteLine("----------");

            Employee em2 = new Manager();
            e2.Name = "Employee em2 = new Manager()";
            e2.NewShow();
        }
    }
}
[C#] new 關鍵字-2

沒有留言:

張貼留言