簡體   English   中英

創建抽象類的對象。 怎么可能

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM