C#中介面、基類與類

iamzxf發表於2015-04-08

    C#中,介面是一個非常重要的概念,它定義了需要實現介面的相關的類需要共同遵守的一個約定,只能包含屬性、方法和函式,不能包含欄位。

    類只能繼承一個類,不能多重繼承。但可以繼承多個介面。繼承介面的類需要實現介面定義的相關屬性、方法和函式。在介面中定義相關成員時,不加任何修飾符,預設為public,在相應的類中實現相應的成員時,修飾符必須是public。當類同時繼承基類和介面時,先繼承基類,再繼承介面。

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

namespace demoInterface
{
    interface IPersonIncome
    {
        double Income { get; }
        void Display();
    }

    class Student:IPersonIncome {
        private string name;
        private double subvention;
        private double scholarship;
        private double grants;

        public Student(string name, double subvention, double scholarship, double grants)
        {
            this.name = name;
            this.subvention = subvention;
            this.scholarship = scholarship;
            this.grants = grants;
        }

        public double Income {
            get {
                return subvention + scholarship + grants;
            }
        }

        public void Display()
        { 
            Console.WriteLine("{0}是一句學生,總收入:{1}",name,Income);
        }        
    }

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

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

    class Manager : Employee, IPersonIncome
    {
        public double Bonus { get; set; }
        public Manager(string name, int age, double salary,double bonus)
            : base(name, age, salary)
        {
            Bonus = bonus;
        }
        public double Income {
            get {
                return Salary + Bonus;
            }
        }

        public void Display()
        {
            Console.WriteLine("{0}是一句經理,總收入:{1}", Name, Income);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student stu = new Student("zxf",100,200,300);
            Manager mng = new Manager("zxf",37,2000,3000);
            stu.Display();
            mng.Display();
            Console.ReadLine();
        }
    }
}



相關文章