方法覆盖在内存中 [英] method overriding in memory

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

问题描述

方法覆盖如何执行?在覆盖中,虚拟,覆盖和新关键字的作用是什么?请解释一下?





例如 -



how does method overriding perform? and what are the role of virtual,overriding, and new key word in overriding? Please Explain?


example like--

class A
    {
        public virtual  void sum()//virtual remove while using new keyword in derive class method
        {
            Console.WriteLine("This is base class method");
        }
    }
    class B:A
    {
        public override void sum()//new in place of override keyword
        {
           Console.WriteLine("This is Derive class method");
        }
    }
<pre>

推荐答案

你在谈论虚拟 - 覆盖对与隐藏



Are you talking about virtual - override pair versus hiding with new?

class Base
{
    public         void A() { Console.WriteLine("Base.A"); }
    public virtual void B() { Console.WriteLine("Base.B"); } // dynamic dispatch
    public virtual void C() { Console.WriteLine("Base.C"); } // dynamic dispatch
    public         void D() { Console.WriteLine("Base.D"); }
}

class Derived : Base
{
    public new      void A() { Console.WriteLine("Derived.A"); } // no warning, hiding is intended
    public override void B() { Console.WriteLine("Derived.B"); } // dynamic dispatch
    public          void C() { Console.WriteLine("Derived.C"); } // warning: hides inherited member --> missing "override" or "new" keyword
    public          void D() { Console.WriteLine("Derived.D"); } // warning: hides inherited member --> missing "new" keyword
}


static void Main(string[] args)
{
    Base inst1 = new Base();
    Base inst2 = new Derived();
    Derived inst3 = new Derived();

    inst1.A(); // Base.A
    inst1.B(); // Base.B
    inst1.C(); // Base.C
    inst1.D(); // Base.D

    inst2.A(); // Base.A
    inst2.B(); // Derived.B --> dynamic dispatch
    inst2.C(); // Base.C    --> should be dynamic dispatch, but hides since missing "override"
    inst2.D(); // Base.D

    inst3.A(); // Derived.A
    inst3.B(); // Derived.B
    inst3.C(); // Derived.C
    inst3.D(); // Derived.D
}





预期用途:

1)基类中的虚拟加上覆盖派生类中的是预期用途。

2)非虚拟加上派生类中没有重新定义也是预期用途。



假设错误(因此,警告),因为它隐藏了基类方法定义:

3) virtual 没有派生的覆盖被认为是错误的用法。

4)非虚拟在派生类中重新定义被认为是错误的用法。



使用关键字 new ,你记录了这个意图使用上面的3)或4)。

我不知道何时建议使用 new



干杯

Andi



Intended use:
1) virtual in the base class plus override in the derived class is the intended use.
2) non-virtual plus no re-definition in the derived class is the intended use too.

Assumed error (thus, a warning) since it hides the base class method definition:
3) virtual without derived override is assumed wrong usage.
4) non-virtual with re-definition in the derived class is assumed wrong usage.

With the keyword new you document this the intended use of 3) or 4) above.
I don''t know when this usage of new is advised.

Cheers
Andi


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

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