C#中類的繼承

iamzxf發表於2015-04-08

C#中類的繼承,繼承類可以訪問基類中protected、public的欄位和屬性,而無法訪問private屬性,程式碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace chap4_4
{
    class Employee
    {
        protected string Name{get;set;}
        public int Age{get;set;}
        public double Salary { get; set; }        

    }

    class Manager : Employee
    {
        public double Bonus { get; set; }

        public Manager(string name, int age, double salary, double bonus)
        {
            this.Name = name;            
            this.Age = age;
            this.Salary = salary;
            this.Bonus = bonus;
        }

        public void disp()
        { 
            Console.WriteLine("{0},{1},{2},{3}",this.Name,this.Age,this.Salary,this.Bonus);
        }
        
    }


    class Program
    {
        static void Main(string[] args)
        {
            Manager mng = new Manager("zxf",23,1200,1000);
            mng.disp();
            Console.ReadLine();            
        }
    }
}

如果在基類中定義了相關解構函式,則可以簡化繼承類的解構函式,如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace chap4_4
{
    class Employee
    {
        protected string Name{get;set;}
        public int Age{get;set;}
        public double Salary { get; set; }
        public Employee(string name, int age, double salary)
        {
            Name = name;
            Age = age;
            Salary = salary;
        }
    }

    class Manager : Employee
    {
        public double Bonus { get; set; }

        public Manager(string name, int age, double salary, double bonus):base(name,age,salary)
        {
            Bonus = bonus;
        }

        public void disp()
        { 
            Console.WriteLine("{0},{1},{2},{3}",this.Name,this.Age,this.Salary,this.Bonus);
        }
        
    }


    class Program
    {
        static void Main(string[] args)
        {
            Manager mng = new Manager("zxf",23,1200,1000);
            mng.disp();
            Console.ReadLine();            
        }
    }
}



相關文章