zoukankan      html  css  js  c++  java
  • abstract与virtual傻傻分不清楚

    最近在CSDN上看到了一个新人求助的帖子,看样子像刚刚学习到面向对象,问的是C#中几个关键字的区别。其中问到了abstract和virtual的区别。

    为此我先查了一下MSDN,看一下微软官方给出的解释:

    abstract:http://msdn.microsoft.com/zh-cn/library/sf985hc5.aspx

    virtual:http://msdn.microsoft.com/zh-cn/library/9fkccyh4.aspx

    我们先看一下微软对abstract的解释:

    abstract 修饰符指示所修饰的内容缺少实现或未完全实现。 abstract 修饰符可用于类、方法、属性、索引器和事件。在类声明中使用 abstract 修饰符以指示某个类只能是其他类的基类。 标记为抽象或包含在抽象类中的成员必须通过从抽象类派生的类来实现。

    之后是virtual的解释:

    virtual 关键字用于修饰方法、属性、索引器或事件声明,并使它们可以在派生类中被重写。

    因此可以知道abstract是用来修士抽象类的,而类中的方法或成员必须通过派生类才能实现,而virtual则可以在方法中写有代码,但可以通过派生类而通过override进行重写。

    下面给出MSDN的事例代码可以让大家更好的理解

    abstract:

    abstract class ShapesClass
    {
        abstract public int Area();
    }
    class Square : ShapesClass
    {
        int side = 0;
    
        public Square(int n)
        {
            side = n;
        }
        // Area method is required to avoid
        // a compile-time error.
        public override int Area()
        {
            return side * side;
        }
    
        static void Main() 
        {
            Square sq = new Square(12);
            Console.WriteLine("Area of the square = {0}", sq.Area());
        }
    }
    

    virtual:

    class MyBaseClass
    {
        // virtual auto-implemented property. Overrides can only
        // provide specialized behavior if they implement get and set accessors.
        public virtual string Name { get; set; }
    
        // ordinary virtual property with backing field
        private int num;
        public virtual int Number
        {
            get { return num; }
            set { num = value; }
        }
    }
    
    
    class MyDerivedClass : MyBaseClass
    {
        private string name;
    
       // Override auto-implemented property with ordinary property
       // to provide specialized accessor behavior.
        public override string Name
        {
            get
            {
                return name;
            }
            set
            {
                if (value != String.Empty)
                {
                    name = value;
                }
                else
                {
                    name = "Unknown";
                }
            }
        }
    
    }
    

      

  • 相关阅读:
    一款开源免费跨浏览器的视频播放器--videojs使用介绍(转)
    forward内部跳转 和redirect重定向跳转的区别
    心理学--斯纳金
    心理学--大脑
    心理学--普及
    经济--国债,外汇
    经济--公积金
    经济--技术分析
    经济--分级基金3
    经济--分级基金
  • 原文地址:https://www.cnblogs.com/xiangsoft/p/2390326.html
Copyright © 2011-2022 走看看