问题描述
C#中的运行时类型和编译时类型之间有什么区别,以及有关虚拟方法调用的含义是什么?
What is the difference between a run-time type and a compile-time type in C# and what implications exist regarding virtual method invocation?
推荐答案
假设我们有两个声明为以下的类: A
和 B
:
Lets say we have two classes A
and B
declared as follows:
internal class A
{
internal virtual void Test() => Console.WriteLine("A.Test()");
}
internal class B : A
{
internal override void Test() => Console.WriteLine("B.Test()");
}
B
继承自 A
并覆盖方法 Test
,该方法将消息打印到控制台。
B
inherits from A
and overrides the method Test
which prints a message to the console.
现在让我们考虑以下语句:
Now lets consider the following statement:
A test = new B();
-
在编译时:编译器只知道变量
test
的类型为A
。他不知道我们实际上是给他一个B
的实例。因此,test
的编译类型为A
。
at compile time: the compiler only knows that the variable
test
is of the typeA
. He does not know that we are actually giving him an instance ofB
. Therefore the compile-type oftest
isA
.
在运行时: test
的类型已知为 B
因此其运行时类型为 B
at run time: the type of test
is known to be B
and therefore has the run time type of B
以下代码语句:
(((A)new B())。Test();
我们正在创建 B
的实例,并将其转换为 A
类型然后对该对象调用 Test()
方法。编译器类型为 A
,运行时类型为 B
。
We are creating an instance of B
casting it into the type A
and invoking the Test()
method on that object. The compiler type is A
and the runtime type is B
.
当编译器要解决 .Test()
调用时,他遇到了问题。因为 A.Test()
是虚拟
,所以编译器不能简单地调用 A.Test
,因为存储的实例可能已覆盖该方法。
When the compiler wants to resolve the .Test()
call he has a problem. Because A.Test()
is virtual
the compiler can not simply call A.Test
because the instance stored might have overridden the method.
编译器本身无法确定调用 A的方法.Test()
或 B.Test()
。调用的方法由运行时确定,而不是由编译器硬编码。
The compile itself can not determine which of the methods to call A.Test()
or B.Test()
. The method which is getting invoked is determined by the runtime and not "hardcoded" by the compiler.
这篇关于C#中的运行时类型与编译时类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!