期待"来自派生的你好".但是得到"基地的你好".
class Program
{
interface IBase
{
void Method();
}
public class Base: IBase
{
public virtual void Method()
{
Console.WriteLine("Hello from the base.");
}
}
public class Derived : Base
{
public virtual new void Method()
{
Console.WriteLine("Hello from the derived.");
}
}
static void Main(string[] args)
{
IBase x = new Derived();
x.Method();
}
}
Run Code Online (Sandbox Code Playgroud)
那么为什么不调用派生类的方法呢?更重要的是,如何在不将x转换为Derived类型的情况下调用派生类方法?
在我的实际应用中,IBase有几个其他相关方法,Derived只替换了IBase中的两个方法.
当您使用new修饰符时,您明确指出该方法不是该层次结构的虚拟分派链的一部分,因此在基类中使用相同名称调用该方法将不会导致重定向到子类.如果您使用override而不是标记方法,new您将看到您希望看到的虚拟分派.
您还需要virtual从派生类的方法中删除,因为您无法将override方法标记为virtual(它已经是).
如果您真的不想覆盖该方法,那么在您的情况下,根本不使用继承可能更合适.您可能只想使用接口:
public interface IFoo
{
void Foo();
}
public class A : IFoo
{
public void Foo()
{
Console.WriteLine("I am A, hear me roar!");
}
}
public class B : IFoo
{
public void Foo()
{
Console.WriteLine("I am B, hear me roar!");
}
}
private static void Main(string[] args)
{
IFoo foo = new A();
foo.Foo();
foo = new B();
foo.Foo();
Console.WriteLine();
Console.WriteLine("Press any key to exit . . .");
Console.ReadKey(true);
}
Run Code Online (Sandbox Code Playgroud)