Does casting create new object?

后端 未结 4 772
别那么骄傲
别那么骄傲 2020-12-10 11:31

I am quite unsure here:

Image i=some image...

Bitmap B=(Bitmap)i;

The B now points to the same object as i. I am confused...I would say th

4条回答
  •  离开以前
    2020-12-10 12:13

    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 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

提交回复
热议问题