【发布时间】: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 应用商店 种。不幸的是WriteableBitmap 是sealed。它的基类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