面试官问我下面的问题
public class A
{
public string GetName()
{
return "A";
}
}
public class B : A
{
public string GetName()
{
return "B";
}
}
public class C : B()
{
public string GetName
{
return "C";
}
}
的输出是什么?
A a = new A();
a.GetName();
a = new B();
a.GetName();
a = new C();
a.GetName();
我说所有人都会给#34; A"。然后他说我需要纠正我的基础知识。
答案 0 :(得分:1)
您要将所有对象(new A()
,new B()
,new C()
)分配给变量A a
。由于它们都被视为类型A
且方法不是虚拟的,因此调用类型A
的实现并返回“A”。
This link提供了更详细的样本说明。
答案 1 :(得分:1)
你的答案是对的;由于缺少virtual
和override
关键字,因此没有应用方法覆盖。
因此,在所有三种情况下,它都会返回输出A
。
如果要应用正确的方法覆盖,则需要将virtual
应用于基类方法,并将override
应用于覆盖基类方法的子类方法。
试试这个:
class Program
{
static void Main(string[] args)
{
A a = new A();
Console.WriteLine(a.GetName());
a = new B();
Console.WriteLine(a.GetName());
a = new C();
Console.WriteLine(a.GetName());
}
}
public class A
{
public virtual string GetName()
{
return "A";
}
}
public class B : A
{
public override string GetName()
{
return "B";
}
}
public class C : B
{
public override string GetName()
{
return "C";
}
}
输出:
A
B
C
答案 2 :(得分:0)
public class B : A
{
public string GetName()
{
return "B";
}
}
与
相同public class B : A
{
public new string GetName()
{
return "B";
}
}
将通过调用接口或基类隐藏方法,
var b = new B(); b.GetName()==> “B”
,而
a a = new B(); a.GetName()===> “A”
这很糟糕,我看到很多人编写这样的代码而不知道新的和覆盖之间有什么区别