接口、继承和';新';关键字

本文关键字:关键字 继承 接口 | 更新日期: 2023-09-27 17:58:56

我想知道是否有人能向我解释一下:

class Program
{
    static void Main()
    {
        AnotherDerivedClass d = new AnotherDerivedClass();
        Console.WriteLine(d.PrintMessage());
        IMsg m = d as IMsg;
        //Why this prints BaseClass.
        //How does it know that IMsg is implemented in the BaseClass.
        Console.WriteLine(m.PrintMessage());
        IMsg n = d as DerivedClass;
        //Why this prints BaseClass and not DerivedClass
        Console.WriteLine(n.PrintMessage());
        Console.Read();
    }
}
public interface IMsg
{
    string PrintMessage();
}
public class BaseClass : IMsg
{
    public string PrintMessage()
    {
        return "BaseClass";
    }
}
public class DerivedClass : BaseClass
{
    public new string PrintMessage()
    {
        return "DerivedClass";
    }
}
public class AnotherDerivedClass : DerivedClass
{
    public new string PrintMessage()
    {
        return "AnotherDerivedClass";
    }
}

接口、继承和';新';关键字

您已经替换了派生类中的实现,而不是重写它们。如果使用BaseClass,将使用原始实现。

你需要使基础中的方法虚拟化:

public class BaseClass : IMsg
{
    public BaseClass()
    {
    }
    public virtual string PrintMessage()
    {
        return "BaseClass";
    }
}

和在派生类中重写:

public class DerivedClass : BaseClass
{
    public DerivedClass()
    {
    }
    public override string PrintMessage()
    {
        return "DerivedClass";
    }
}

以获得您指定的行为。