Does casting create new object?

后端 未结 4 776
别那么骄傲
别那么骄傲 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:02

    What you're doing doesn't look sensible! A Bitmap is a subclass of Image, so you can always take a Bitmap object and refer to it as an Image, but you can't guarantee that any particular Image is a Bitmap. If it isn't, you will end up with an exception being thrown.

    You can create a new Bitmap from an Image, but you have to do that by creating a new instance, like

    Image i = some image...
    Bitmap b = new Bitmap(i);
    

    That is not casting, that is creating a new Bitmap object, but is a) legal and b) sensible.

提交回复
热议问题