方法覆盖和方法隐藏 [英] method overriding and method hiding

查看:66
本文介绍了方法覆盖和方法隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class BaseAppXmlLogReaders
    {
        public virtual void WriteLog() { }
        public void Add()
        {
        }
    }
    class DerivedAppXmlLogReaders : BaseAppXmlLogReaders
    {
        public override void WriteLog()
        {

        }
        public new void Add()
        { }
    }

    class Demo
    {
        public static void Main()
        {
            BaseAppXmlLogReaders obj = new DerivedAppXmlLogReaders();
            obj.Add();//Call base class method
            obj.WriteLog();//call derived class method
        }
    }







我有点混淆但是它产生了DerivedAppXmlLogReaders的对象,但它调用了基类的Add()方法和派生类的WriteLog()方法。

classBase obj = new classDerived();表示创建类的对象创建即时任意类的新东西然后创建该类的对象然后为什么..




I am little bit confuse however it makes object of DerivedAppXmlLogReaders but it calls Add() method of base class and WriteLog() method of derived class.
classBase obj =new classDerived(); Means object of dervied class created i m right whatever class infront of new then creates object of that class then WHY..

推荐答案

参见文档 [ ^ ]关于此规则。
See the documentation[^] on the rules for this.


属性virtual使编译器清楚地知道需要创建虚方法表。这意味着对对象(类或基类)的调用不会直接调用该类的方法,但会查找给定实际类的方法。



如果不使用virtual / override,编译器只会调用声明类型的方法。编译器可以在编译时确定这一点。



使用virtual / override时,它将查看当时的实际类型。要调用的方法在运行时确定,因此增加了一点开销。



祝你好运!
The attribute virtual makes it clear to the compiler that a virtual method table needs to be created. This means that a call to an object (class or base class) will not invoke the method of that class directly but will look up the method for the actual class given.

Without the use of virtual/override the compiler will just call the method of the declared type. The compiler can therefor determine this at compile time.

With the use virtual/override it will look at the actual type at that moment. The method to be called is determined at runtime and therefor adds a little overhead.

Good luck!


这篇关于方法覆盖和方法隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆