小编est*_*son的帖子

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

期待"来自派生的你好".但是得到"基地的你好".

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中的两个方法.

c# inheritance

7
推荐指数
1
解决办法
6173
查看次数

标签 统计

c# ×1

inheritance ×1