编译时和运行时的铸件C# [英] Compile-time and runtime casting c#

查看:162
本文介绍了编译时和运行时的铸件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?

推荐答案

  • Upcasts可以在编译时检查 - 类型系统保证了转换成功
  • 在向下转换不能(一般),在编译时检查,所以他们总是检查在运行时。
  • 在不相关类型不能投给对方。

编译器只考虑静态类型。运行时检查动态(运行时)类型。 看着你的例子:

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 其他。这是无关派生这样的转换失败在编译时。

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 现在基本。类型的东西基本可能的具有动态类型派生,因此这是一个沮丧的。一般来说,编译器不知道从静态类型的 X ,如果它的运行时类型基本,<$对基本的其他一些子类,C $ C>导出。这样的铸造是否允许的决定留给运行时

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

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