gpt4 book ai didi

c# - 接口(interface)、继承和 'new' 关键字

转载 作者:太空宇宙 更新时间:2023-11-03 18:43:44 27 4
gpt4 key购买 nike

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

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

获取您指定的行为。

关于c# - 接口(interface)、继承和 'new' 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6307643/

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