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.”