接口,继承和'new'关键字

时间:2011-06-10 14:18:52

标签: c# inheritance interface

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

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

1 个答案:

答案 0 :(得分:7)

您已在派生类中替换了实现,而不是覆盖它们。如果您使用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";
    }
}

获取您指定的行为。