更新时间:2022-12-11 17:12:10
原因如下:http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.110%29.aspx [ ^ ].
还是没有得到?看看等于"行.
还是没有得到?现在,让我们看一下定义:
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx [ ^ ].
如您所见,System.Windows.Media.ImageSource
是System.Windows.Media.Imaging.BitmapImage
的间接基类.这意味着BitmapImage
始终为ImageSource
,但ImageSource
并非始终为BitmapImage
.知道了吗?不是吗?
看,它们是 可分配的 ,就像这样:
Here is why: http://msdn.microsoft.com/en-us/library/cscsdfbt%28v=vs.110%29.aspx[^].
Still did not get it? Look at "is equivalent to" line.
Still did not get it? Now, let''s look at the definitions:
http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx[^].
As you can see,System.Windows.Media.ImageSource
is the indirect base class ofSystem.Windows.Media.Imaging.BitmapImage
. It means, theBitmapImage
is alwaysImageSource
, butImageSource
is not alwaysBitmapImage
. Got it, finally? No?
Look, they are assignable like that:
BitmapImage bitmap = //...
ImageSource src = bitmap;
但不是反方向.相反,您可以正确使用as
.如果运算符失败,则该操作符返回null;如果成功,则返回对同一对象的引用,其编译时间类型为ImageSource
,而运行时类型为BitmapImage
.在您的情况下,null表示您的对象不是 BitmapImage
.
另请参阅我过去的答案:运行时多态VS编译时多态 [ http://social.msdn.microsoft.com /forums/zh-CN/wpf/thread/8327dd31-2db1-4daa-a81c-aff60b63fee6/ [ Twain对于WPF应用程序-看起来没手感 [
but not in reverse direction. In reverse direction, you rightfully can use as
. This operator returns null if unsuccessful and reference to the same object if successful, with the compile-time type of ImageSource
and run-time type of BitmapImage
. In your case, null indicated that your object is not BitmapImage
.
Please see also my past answer: run-time polymorphism VS compile-time polymorphism[^].
Now, what to do? You simply should forget about BitmapImage
, which you don''t have and don''t need. Any ImageSource
can be serialized into array of bytes. Please see:
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/8327dd31-2db1-4daa-a81c-aff60b63fee6/[^].
Please see this CodeProject article on TWAIN for WPF: Twain for WPF Applications - Look Ma, No Handles[^].