c# – 为什么调用基类方法而不是派生类方法?
发布时间:2020-12-15 18:32:43 所属栏目:百科 来源:网络整理
导读:期待“来自派生的你好”.但是得到“基地的你好”. 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
期待“来自派生的你好”.但是得到“基地的你好”.
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标记方法,那么您将看到您希望看到的虚拟分派.
您还需要从派生类的方法中删除虚拟,因为您无法将覆盖方法标记为虚拟(它已经是). 如果您真的不想覆盖该方法,那么在您的情况下,根本不使用继承可能更合适.您可能只想使用接口: 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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |