Workaround for inheriting from sealed derived clas

2020-03-31 02:16发布

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条回答
狗以群分
2楼-- · 2020-03-31 02:50

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;
    }
}
查看更多
登录 后发表回答