是否创建新对象? [英] Does casting create new object?

查看:198
本文介绍了是否创建新对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里很不确定:

Image i=some image...

Bitmap B=(Bitmap)i;

B现在指向与i相同的对象。我很困惑...我会说Bitmap B将指向映射到位图的新的实例,但显然不是这样。

The B now points to the same object as i. I am confused...I would say that Bitmap B will point to new instance of Image that is casted to bitmap but it is obviously not the case. Then I just do not get how it works here.

推荐答案

铸造不会创建一个新对象(至少,除非< a href =http://msdn.microsoft.com/en-us/library/8edha89s%28v=vs.80%29.aspx>新的转换运算符,这是非常罕见的,数字类型,并且不适用于您的示例)。它只是指示编译器如何处理对象。在你出现的情况下,你告诉编译器不要担心,相信我, B 实际上是一个 Bitmap 。如果事实证明你已经告诉它一个fib,运行时将抓住它通过在运行时引发 InvalidCastException

Casting does not create a new object (at least, not unless new conversion operators have been defined, which is uncommon in non-numeric types, and doesn't apply in your example). It merely instructs the compiler how to "treat" an object. In the case you present, you're telling the compiler "don't worry, trust me, B is actually a Bitmap". If it turns out you've told it a fib, the runtime will catch you on it by throwing an InvalidCastException at runtime.

MSDN 提供了一些详细信息。

MSDN has some more information.


转换是一种显式通知编译器您打算进行转换并且您知道可能发生数据丢失的方法

A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur

这篇关于是否创建新对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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