Call a new subclass method from the base class

I have classes like this

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new C();

            a.method();
            Console.ReadLine();
        }
    }

    public class A
    {
        public virtual void method()
        {
            Console.WriteLine("METHOD FROM A");
        }
    }

    public class B : A { }

    public class C : B
    {
        public override void method()
        {
            Console.WriteLine("METHOD FROM C");
        }
    }
}

It works correctly, prints "METHOD FROM C"

BUT

If I have this situation,

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            A a = new C();

            a.method();
            Console.ReadLine();
        }
    }

    public class A
    {
        public void method()
        {
            Console.WriteLine("METHOD FROM A");
        }
    }

    public class B : A { }

    public class C : B
    {
        public new void method()
        {
            Console.WriteLine("METHOD FROM C");
        }
    }
}

he prints "METHOD OF A". How can I get the same behavior of the first example without accepting the declaration of the transform method or change with overriding?

+3
source share
3 answers

You cannot - this is a difference in behavior - this is the purpose of using virtual / redefinition.

When you declare a method with "new", you say, "I know that I am hiding a method with the same signature, and not redefining it, I do not want polymorphic behavior."

, "", " , ".

? , ? , - . , , .

, , :

C c = new C();
c.method();

.

+11

, .

static void Main(string[] args)
    {
        A a = new C();

        (a as C).method();

        Console.ReadLine();
    }
+2

You can use a dynamic keyword to call this method.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic a = new C();

            a.method();
            Console.ReadLine();
        }
    }

    public class A
    {
        public void method()
        {
            Console.WriteLine("METHOD FROM A");
        }
    }

    public class B : A { }

    public class C : B
    {
        public new void method()
        {
            Console.WriteLine("METHOD FROM C");
        }
    }
}
+1
source

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


All Articles