C# virtual, base, override

先看这样一段代码:

namespace @virtual
{
    class A
    {
        public void print()
        {
            Console.WriteLine("base");
        }
    }
    class a :A{
        public void print()
        {
            Console.WriteLine("derive");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A p = new A();
            p.print();
            p = new a();
            p.print();
            Console.ReadKey();
        }
    }
}

output:
base
base

p调用了基类的同名方法,如果想使用子类的print()需要用 virtual修饰基类的print()再在子类中 override重写print(),那样才能调用派生类的方法

namespace @virtual
{
    class A
    {
        public virtual void print()
        {
            Console.WriteLine("base");
        }
    }
    class a :A{
        public override void print()
        {
            Console.WriteLine("derive");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A p = new A();
            p.print();
            p = new a();
            p.print();
            Console.ReadKey();
        }
    }
}

output:
base
derive

它达到的效果和下面的代码是一样的:


namespace @virtual
{
    class A
    {
        public void print()
        {
            Console.WriteLine("base");
        }
    }
    class a :A{
        public void print()
        {
            Console.WriteLine("derive");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            A p = new A();
            p.print();
            a p1 = new a();
            p1.print();
            Console.ReadKey();
        }
    }
}

output:
base
derive

base则是对在派生类里对基类成员的访问。在基类数据成员或方法被子类同名成员隐藏的情况下,它能发挥巨大的作用。

namespace @base
{
    class A
    {
        public void print()
        {
            Console.WriteLine("base");
        }
    }
    class a :A{
        public void print()
        {
            Console.WriteLine("derive");
        }
        public void fatherPrint()
        {
            base.print();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            a p1 = new a();
            p1.fatherPrint();
            p1.print();
            Console.ReadKey();
        }
    }
}

output:
base
derive

你可能感兴趣的:(C#)