C#中的运行时类型与编译时类型 [英] Run-time type vs compile-time type in C#

查看:151
本文介绍了C#中的运行时类型与编译时类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.


在C#中运行时类型和编译时类型之间有什么区别

What is the difference between a run-time type and a compile-time type in C#

现在让我们考虑以下语句:

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 type A. He does not know that we are actually giving him an instance of B. Therefore the compile-type of test is A.

在运行时: test 的类型已知为 B 因此其运行时类型为 B

at run time: the type of test is known to be B and therefore has the run time type of B


以及有关虚拟方法调用的含义

and what implications exist regarding virtual method invocation

以下代码语句:

(((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#中的运行时类型与编译时类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆