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");
            }
        }
    
    }
  • 相关阅读:
    Python基础之zip和enumerate
    python3中map()函数用法
    python列表推导式
    python面试常问的几个内置装饰器:@staticmethod、@classmethod和@property
    linux的解压与压缩
    python中 s f各种转移字符含义
    fixture 调用函数名传参(转载)
    3.css选择器
    实战有感3
    实战有感2-轮播图
  • 原文地址:https://www.cnblogs.com/dearbeans/p/14198974.html
Copyright © 2011-2022 走看看