【问题标题】:Workaround for inheriting from sealed derived class?从密封派生类继承的解决方法?
【发布时间】:2013-11-19 22:54:54
【问题描述】:

我想从派生类SealedDerived 派生,但我不能,因为该类是sealed。如果我从基类Base 派生,有什么办法可以“作弊”并将this 引用重定向到SealedDerived 类的对象?

例如,像这样:

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?
    }
}

编辑根据要求,这里是上下文:我正在将一个广泛使用System.Drawing.Bitmap 的.NET 类库移植到一个Windows 应用商店 库。我解决 Windows 应用商店 中缺少 System.Drawing.Bitmap 类的主要想法是实现一个虚拟的 Bitmap 类,该类将从 WriteableBitmap 继承,从而能够返回Windows 应用商店 种。不幸的是WriteableBitmapsealed。它的基类BitmapSource(当然)不是密封的,但另一方面几乎没有提供任何操作图像的方法。这就是我的两难选择。

类似这样的:

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...
      ...
    }
  }
}

理想情况下,我希望我的假 Bitmap 代表 Windows 应用商店 类型的位图类型,例如,我可以将我的假 Bitmap 类分配给 Image.Source

【问题讨论】:

  • 不,这行不通。您可能会使用合成来代替,但我们无法确定。您为什么不告诉我们您要解决的更大问题,我们也许可以提供更多帮助。
  • 约翰所说的。此外,根据您要完成的工作,扩展方法可能是一种选择。
  • 继承我认为这里不是正确的选择,因为 jon saied 试图解释更多,也许我们会为您提供正确的设计模式,例如尝试看看dofactory.com/Framework/Framework.aspx
  • 也许没有有用的 cmets :)
  • 感谢@JonSkeet 和其他人花时间回复。我已经用一些背景背景更新了这个问题。

标签: c# oop inheritance


【解决方案1】:

添加为答案,以便我可以提供代码示例,但请随时作为评论。如果您觉得必须保持这种模式,那么隐式类型转换可能会对您有所帮助。在不知道您的图像库在做什么的情况下,这只会将问题推得更深,因为无论采用何种方法,任何Graphics.FromImage 都无法正常工作。如果您的库仅限于GetPixelSetPixelLockBits,您也许可以通过足够的努力来完成这项工作。

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;
    }
}

【讨论】:

  • 谢谢,大卫!我实际上开始尝试与您在上面描述的相同的方法。我知道内部工作会带来新的挑战,但我会一步一步来:-)我会测试一下,如果它有效,我会很乐意接受答案。
猜你喜欢
  • 1970-01-01
  • 2014-12-23
  • 2013-05-20
  • 2015-01-20
  • 2023-04-09
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多