문제

Bit of a noobie question but hey ho.

Example:

BaseClass bc = new ExtendedClass(); //Assume ExtendedClass inherits from BaseClass
((BaseClass)bc).ExtendedMethod();
bc.ExtendedMethod();
((ExtendedClass)bc).ExtendedMethod(); //overridden in ExtendedClass

ExtendedClass ec = new ExtendedClass();
((BaseClass)ec).ExtendedMethod();
ec.ExtendedMethod();
((ExtendedClass)ec).ExtendedMethod(); //overridden in ExtendedClass 

?

What implementations will bc.ExtendedMethod(); and ec.ExtendedMethod(); call at runtime? Will they be different? I assume the casted calls will call the specific implementation within the class.

edit: added relevant tag.

도움이 되었습니까?

해결책

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

public class Extend : Base
{
    public new void Extends()
    {
        Console.WriteLine("Extend class");
    }
}


public class Program
{
    public static void Main()
    {

        Base b = new Base();
        b.Extends();

        Extend e = new Extend();
        e.Extends();

        Base be = new Extend();
        be.Extends();

        Console.Read();

   }

}

Results in the following output:

Base class
Extend class
Base class

Note you can also use the new keyword in the Extend class to hide the base Extends function.

public new void Extends() 
{

}

다른 팁

In all three cases the overridden implementation of ExtendedMethod will be called, as you are creating an instance of ExtendedClass. After all, this is what polymorphism is all about.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top