Workaround for inheriting from sealed derived class?

≡放荡痞女 提交于 2020-01-30 02:53:13

问题


I want to derive from a derived class SealedDerived but I can't because the class is sealed. If I instead derive from the base class Base, is there any way I can "cheat" and redirect the this reference to an object of the SealedDerived class?

For example, like this:

public class Base { ... }

public sealed class SealedDerived : Base { ... }

public class MyDerivedClass : Base
{
    public MyDerivedClass()
    {
        this = new SealedDerived();  // Won't work, but is there another way?
    }
}

EDIT Upon request, here is the context: I am porting a .NET class library that makes extensive use of System.Drawing.Bitmap to a Windows Store library. My primary idea to workaround the lack of the System.Drawing.Bitmap class in Windows Store was to implement a dummy Bitmap class that would inherit from WriteableBitmap and thereby be able to return a bitmap object of the Windows Store kind. Unfortunately WriteableBitmap is sealed. Its base class BitmapSource is (of course) not sealed, but on the other hand provides practically no methods for manipulating the image. Hence my dilemma.

Something like this:

using Windows.UI.Xaml.Media.Imaging;

namespace System.Drawing {
  public class Bitmap : BitmapSource {
    public Bitmap(int width, int height) {
      this = new WriteableBitmap(width, height);  // Will not work...
      ...
    }
  }
}

Ideally, I want my fake Bitmap to represent a bitmap type of the Windows Store kind, so that I for example can assign my fake Bitmap class to an Image.Source.


回答1:


Added as an answer so I could provided the code sample but feel free to take as a comment. If you feel you must keep to this pattern an implicit type cast may help you. Without knowing what your image library is doing this just pushes the problem deeper as any Graphics.FromImage was never going to work regardless of approach. If your library is restricted to GetPixel, SetPixel and LockBits you may be able to make this work with enough effort.

public class Bitmap
{
    public static implicit operator WriteableBitmap(Bitmap bitmap)
    {
        return bitmap._internalBitmap;
    }

    private readonly WriteableBitmap _internalBitmap;

    public Bitmap(int width, int height)
    {
        _internalBitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgra32, null);
    }
}

public partial class MainWindow : Window
{
    public Image XamlImage { get; set; }

    public MainWindow()
    {
        var bitmap = new Bitmap(100, 100);
        XamlImage.Source = bitmap;
    }
}


来源:https://stackoverflow.com/questions/20083901/workaround-for-inheriting-from-sealed-derived-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!