问题描述
我在这里很不确定:
Image i=some image...
Bitmap B=(Bitmap)i;
B 现在指向与 i 相同的对象.我很困惑......我会说位图 B 将指向转换为位图的 Image 的新实例,但显然情况并非如此.然后我就是不明白它在这里是如何工作的.
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.
推荐答案
Casting 不会创建新对象(至少,除非 新的转换运算符已被定义,这在非数字类型中并不常见,并且不适用于您的示例).它只是指示编译器如何处理"一个对象.在您提供的情况下,您是在告诉编译器别担心,相信我,B
实际上是一个 Bitmap
".如果事实证明你告诉了它一个谎言,运行时会通过在运行时抛出一个 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 有更多信息.
强制转换是一种明确通知编译器您打算进行转换并且您知道可能会发生数据丢失的方式
这篇关于铸造会创建新对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!