zoukankan      html  css  js  c++  java
  • 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");
            }
        }
    
    }
  • 相关阅读:
    管理心理学[9095]
    汽车文化[1196]
    小四轴——空心杯电机引起的电源干扰
    38 时序电路扩展2
    37 时序电路扩展1
    36 时序电路的动态特性分析2
    35 时序电路的动态特性分析1
    34 同步时序电路的设计方法2
    33 同步时序电路的设计方法1
    60. 第k个排列
  • 原文地址:https://www.cnblogs.com/dearbeans/p/14198974.html
Copyright © 2011-2022 走看看