gpt4 book ai didi

c# - 为什么调用基类方法而不是派生类方法?

转载 作者:太空狗 更新时间:2023-10-29 20:00:01 27 4
gpt4 key购买 nike

期待“派生的问候”。但收到“来自基地的问候”。

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();
}
}

那么为什么不调用派生类的方法。更重要的是,如何在不将 x 强制转换为 Derived 类型的情况下调用派生类方法?

在我的实际应用中,IBase还有其他几个相关的方法,而Derived只替换了IBase中的两个方法。

最佳答案

当您使用 new 修饰符时,您明确表示该方法不是该层次结构的虚拟调度链的一部分,因此在基类中调用同名方法不会产生结果重定向到子类。如果您使用 override 而不是 new 标记该方法,那么您将看到您期望看到的虚拟分派(dispatch)。

您还需要从派生类的方法中删除 virtual,因为您不能将 override 方法标记为 virtual(它已经是) .

如果您真的不想覆盖该方法,那么在您的情况下,根本不使用继承可能更合适。您可能只想独占使用接口(interface):

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);
}

关于c# - 为什么调用基类方法而不是派生类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13363534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com