C Sharp/Inheritance

維基教科書,自由的教學讀本
跳至導覽 跳至搜尋

繼承的要點:

  1. 派生類包含了被繼承類的成員和數據
  2. 構造函數和析構函數不能被繼承
  3. 派生類的成員的可訪問性依賴於在被繼承類的成員的可訪問性
  4. 派生類成員可覆蓋被繼承類成員
using System;
using System.Text;

namespace ContainmentInheritance
{
    class Room
    {
        public int length;
        public int width;
        public int height;

        public Room(int l, int w, int h)
        {
            length = l;
            width = w;
            height = h;
        }
    }

    class Home
    {
        int numberOfRooms;
        int plotSize;
        string locality;
        string name;

        // create an object of class Room inside class Home
        Room studyRoom = new Room(10, 12, 12);

        public Home()
        {
            numberOfRooms = 1;
            plotSize = 1000;
            locality = "Versova";
            name = "study room";
        }

        public void Display()
        {
            Console.WriteLine("MyHome has {0} rooms", numberOfRooms);
            Console.WriteLine("Plot size is {0}", plotSize);
            Console.WriteLine("Locality is {0}", locality);

            int area = studyRoom.length*studyRoom.width;
            Console.WriteLine("Area of the {0} room is {1}", name, area);
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Home myhome = new Home();
            myhome.Display();

            Console.ReadLine();
        }
    }
}


虛方法[編輯]

public class Resource : IDisposable
{
    private bool _isClosed = false;    // good programming practice initialise, although default
    
    protected virtual void Close()
    {
        Console.WriteLine("Base resource closer called!");
    }
    
    ~Resource()
    {
        Dispose();
    }
    
    public void Dispose()
    {
        if (!_isClosed)
        {
            Console.WriteLine("Disposing resource and calling the Close() method...");
            _isClosed = true;
            Close();
        }
    }
}

public class AnotherTypeOfResource : Resource
{
    protected override void Close()
    {
        Console.WriteLine("Another type of resource closer called!");
    }
}

public class VirtualMethodDemo
{
    public static void Main()
    {
        Resource res = new Resource();
        AnotherTypeOfResource res2 = new AnotherTypeOfResource();
        
        res.Dispose();  // Resource.Close() will be called.
        res2.Dispose(); // Even though Dispose() is part of the Resource class, 
                        // the Resource class will call AnotherTypeOfResource.Close()!
    }
}

繼承關鍵字[編輯]

C#的繼承使用:運算符。

public class Executive : Employee

虛方法使用關鍵字Template:C sharp/kw.

public virtual void Write(string text)
{
    System.Console.WriteLine("Text:{0}", text);
}

覆蓋基類的虛方法使用關鍵字 Template:C sharp/kw keyword:

public override void Write(string  text)
{
    System.Console.WriteLine(text);
}

派生類的同名方法如果不使用newoverride關鍵字聲明則會被編譯警告:[1]

abstract class ShapesA
{
    abstract public int Area(); // abstract!
}

class Square : ShapesA
{
    int x, y;

    public int Area() // Error: missing 'override' or 'new'
    {
        return x * y;
    }
} 

class Shapes
{
    virtual public int Area() { return 0; } // it is virtual now!
}

class Square : Shapes
{
    int x, y;

    public int Area() // no explicit 'override' or 'new' required
    { return x * y; }
}


參考文獻[編輯]

  1. Greg Beech(2010年3月9日).C# design: Why is new/override required on abstract methods but not on virtual methods? / Answer.eFreedom.於2011年8月11日查閱.原文:「Using either the C# 3.0 compiler as shipped in .NET 3.5 SP1, or the C# 4.0 compiler as shipped in .NET 4.0, I get the following error for your first example: [...] And the following warning for the second one: [...] In the first case it's an error because you aren't actually overriding the base method, which means there is no implementation for the abstract method in a concrete class. In the second case it's a warning because the code is technically correct, but the compiler suspects that it isn't what you meant. This is one of the reasons it's generally a good idea to enable the "treat warnings as errors" compilation setting.」