[英]Create object of abstract class. How possible
為什么有可能? :
BitmapSource i = Imaging.CreateBitmapSourceFromHBitmap(...);
我正在寫一些應用程序ni找到這一行並且我是cunfused,因為MSDN說BitmapSource是抽象類。
BitmapSource
是一個抽象類,因此不能直接創建,但Imaging.CreateBitmapSourceFromHBitmap
返回從繼承一些具體類BitmapSource
,因此可以“投”到BitmapSource
。
它有一個抽象的Animal
類,但有一個繼承自它的具體Giraffe
類:
Animal a = new Animal(); // illegal
Animal a = Zoo.CreateAnimalFromName("Giraffe"); // valid - returns a Giraffe instance
對Imaging.CreateBitmapSourceFromHBitmap
的調用返回一些繼承自BitmapSource
具體類。 因此,此調用不會創建抽象類BitmapSource
的實例。 你只是對此感到困惑。
為了簡化這種情況,這類似於
Animal an1 = DogFactory.createDog();
或者
Animal an2 = CatFactory.createCat();
如果我們假設Animal
是一個抽象類,而Cat
和Dog
是繼承自Animal
具體類。
BitmapSource
是一個抽象類,但Imaging.CreateBitmapSourceFromHBitmap
創建一個具有類型為具體子類InteropBitmap
的對象,您可以在.NET參考源中看到它:
unsafe public static BitmapSource CreateBitmapSourceFromHBitmap(
IntPtr bitmap,
IntPtr palette,
Int32Rect sourceRect,
BitmapSizeOptions sizeOptions)
{
SecurityHelper.DemandUnmanagedCode();
// CR: [....] (1681459)
return CriticalCreateBitmapSourceFromHBitmap(bitmap, palette, sourceRect, sizeOptions, WICBitmapAlphaChannelOption.WICBitmapUseAlpha);
}
unsafe internal static BitmapSource CriticalCreateBitmapSourceFromHBitmap(
IntPtr bitmap,
IntPtr palette,
Int32Rect sourceRect,
BitmapSizeOptions sizeOptions,
WICBitmapAlphaChannelOption alphaOptions)
{
if (bitmap == IntPtr.Zero)
{
throw new ArgumentNullException("bitmap");
}
return new InteropBitmap(bitmap, palette, sourceRect, sizeOptions, alphaOptions); // use the critical version
}
並且您可以將InteropBitmap
分配給BitmapSource
類型變量,因為它是它的基類(直接或不是),完全如下:
interface ISomeInterface { };
abstract class SomeBaseClass : ISomeInterfac { };
class SomeClass : SomeBaseClass { };
然后你可以:
ISomeInterface var1 = new SomeClass();
要么:
SomeBaseClass var2 = new SomeClass();
最后你可以創建一些隱藏創建對象的工廠方法:
class SomeFactoryClass
{
public SomeBaseClass CreateObject() { return new SomeClass(); }
}
SomeBaseClass var3 = SomeFactoryClass.CreateObject();
正如上面的.NET參考源代碼所示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.