How can we override a method in a child class without using "virtual" in the parent class

This is an interview question. Is it possible to override a method without a virtual pointer in the parent method?

+3
source share
7 answers

They probably wanted you to say, "Use the keyword newto hide the method." Which technically does not cancel the method. if you have

class Base
{
    public void Bar() { Console.WriteLine("Base"); }
}

class Derived : Base
{
    public new void Bar() { Console.WriteLine("Derived"); }
}

And then you wrote

Derived derived = new Derived();
derived.Bar();
((Base)derived).Bar();

You will see different results. Thus, functions that use the base class will receive results for the base method, and functions that use the derived class will receive results for the new method.

+19
source

. , new:

class Foo
{
    public void Bar() {}
}

class FooChild : Foo
{
    new public void Bar() {}
}

, Bar() ( FooChild Foo), , "" .

+4

. , -. "", :

class Base
{
    protected Action m_action;

    public Base()
    {
        m_action = () => Console.WriteLine("Base Class");
    }
    public void NonVirtual()
    {
        m_action();
    }
}

class Derived : Base
{
    public Derived()
    {
        m_action = () => Console.WriteLine("Derived Class");
    }
}

class Program
{
    static void Main (string[] args)
    {
        Base baseClass = new Base();
        Derived derivedClass = new Derived();
        Base derivedAsBase = derivedClass;

        Console.WriteLine("Calling Base:");
        baseClass.NonVirtual();

        Console.WriteLine("Calling Derived:");
        derivedClass.NonVirtual();

        Console.WriteLine("Calling Derived as Base:");
        derivedAsBase.NonVirtual();

        Console.ReadKey();
    }
}

:

Calling Base:
Base Class
Calling Derived:
Derived Class
Calling Derived as Base:
Derived Class

: , .

+1

"new" , , T, , typeof (DerivedClass).IsAssignableFrom(typeof (T)). . , , , .

, . , , . , , "" "" , - , "" vtables ( ).

0
source

No, it will be a function of concealment.

0
source

If redefinition of virtual public methods was possible, we would have much more powerful bullying. No, it's not possible to override non-virtual members, just hide them using newkeyword .

0
source

so we can do this using the new keyword.

using System;

class Example
{
    static void Main()
    {
        Foo f = new Foo();
        f.M();

        Foo b = new Bar();
        b.M();
    }
}

class Foo
{
    public void M()
    {
        Console.WriteLine("Foo.M");
    }
}

class Bar : Foo
{
    public new void M()
    {
        Console.WriteLine("Bar.M");
    }
}
0
source

Source: https://habr.com/ru/post/1762994/


All Articles