c# 虚方法virtual的使用

基类可以定义并实现 方法,派生类可以 重写这些方法,即派生类提供自己的定义和实现。 在运行时,客户端代码调用该方法,CLR 查找对象的运行时类型,并调用虚方法的重写方法。 因此,您可以在源代码中调用基类的方法,但执行该方法的派生类版本。

示例:

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Shape shape = new Shape();
            //shape.X = 3;//错误
            shape.Draw();
            Circle circle = new Circle();
            circle.Draw();
            Triangle triangle = new Triangle();
            triangle.Draw();
            Console.ReadLine();
        }
    }

    public class Shape
    {
        private int x;

        public int X { get => x; private set => x = value; }

        public int Height { get; set; }

        public virtual void Draw()
        {
            Console.WriteLine("画图");
        }
    }

    public class Circle : Shape
    {
        //使用override重写父类的同名方法
        public override void Draw()
        {
            Console.WriteLine("画图-Circle");
        }
    }

    public class Triangle : Shape
    {
        //使用new覆盖父类的同名方法
        public new  void Draw()
        {
            Console.WriteLine("画图-triangle");
        }
    }

}
posted @ 2020-12-27 21:52  陈胜威  阅读(561)  评论(0编辑  收藏  举报