任何人都可以解释这段代码的行为吗,因为我正在研究多态性,所以我偶然想到了这段代码,而且我真的对其行为感到困惑:
public class Book
{
public virtual void Method()
{
Console.WriteLine("Book/ I am here in "+ GetType().Name);
}
}
class Chapter : Book
{
public new void Method()
{
Console.WriteLine("Chapter/ I am here in "+ GetType().Name);
}
static void Main()
{
Book myBook = new Chapter() ;
myBook.Method();
}
}
该程序的输出是
Book/ I am here in Chapter
这意味着实例调用了 book 类中的方法,但获取了类型 chapter
。
GetType()
方法是否取决于它调用的实例,而不是它所在的类?
最佳答案
是的,GetType()
在运行时从对象(实例)获取实际类型。
如果您更改了public new void Method()
public override void Method()
它会打印出另一行。
参见MSDN :
Return Value
Type: System.Type
The exact runtime type of the current instance.
关于c# - 多态性:被调用方法的真实类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610747/