编译时和运行时强制转换

编译时和运行时强制转换

本文介绍了编译时和运行时强制转换 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么在编译时检查 C# 中的某些强制转换,而在其他情况下则将责任转储到 CLR 上.如上所述,两者都不正确,但处理方式不同.

I was wondering why some casts in C# are checked at compile-time whereas in other cases the responsibility is dumped on CLR. Like above both are incorrect but handled in a different way.

class Base { }
class Derived : Base { }
class Other { }

static void Main(string[] args)
{
    Derived d = (Derived)new Base();     //Runtime       InvalidCastException
    Derived d = (Derived)new Other();    //Compile-time  Cannot convert type...
}

在阅读深入了解 C#"时,我发现了有关此主题的信息,作者说:
如果编译器发现该转换实际上不可能工作,则会触发编译错误——如果理论上允许但在执行时实际上不正确,CLR 将抛出异常."

While reading "C# in depth" I've found the information on this topic where autor says:
"If the compiler spots that it’s actually impossible for that cast to work, it’ll trigger a compilation error—and if it’s theoretically allowed but actually incorrect at execution time, the CLR will throw an exception."

理论上"是指通过继承层次结构(对象之间的另一种亲缘关系?)连接还是编译器的内部业务?

Does 'theoretically' mean connected by inheritance hierarchy (some another affinity between objects ?) or it is compiler's internal business?

推荐答案

  • 可以在编译时检查向上转换 - 类型系统保证转换成功.
  • Downcasts 不能(通常)在编译时检查,所以它们总是在运行时检查.
  • 不相关的类型不能相互转换.
  • 编译器只考虑静态类型.运行时检查动态(运行时)类型.查看您的示例:

    The compiler considers only the static types. The runtime checks the dynamic (runtime) type.Looking at your examples:

    Other x = new Other();
    Derived d = (Derived)x;
    

    x 的静态类型是 Other.这与 Derived 无关,因此转换在编译时失败.

    The static type of x is Other. This is unrelated to Derived so the cast fails at compile time.

    Base x = new Base();
    Derived d = (Derived)x;
    

    x 的静态类型现在是 Base.Base 类型的东西可能具有动态类型Derived,所以这是一个向下的转换.一般来说,编译器无法从 x 的静态类型知道它的运行时类型是否是基础.所以是否允许强制转换由运行时决定.

    The static type of x is now Base. Something of type Base might have dynamic type Derived, so this is a downcast. In general the compiler can't know from the static type of x if it the runtime type is Base, Derived, of some other subclass of Base. So the decision of whether the cast is allowed is left to the runtime.

    这篇关于编译时和运行时强制转换 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:51