C# 从密封的派生类继承的变通方法?
我想从派生类C# 从密封的派生类继承的变通方法?,c#,oop,inheritance,C#,Oop,Inheritance,我想从派生类SealedDerived派生,但我不能,因为该类是sealed。如果我从基类base派生,是否有任何方法可以“欺骗”并将此引用重定向到SealedDerived类的对象 例如,像这样: public class Base { ... } public sealed class SealedDerived : Base { ... } public class MyDerivedClass : Base { public MyDerivedClass() {
SealedDerived
派生,但我不能,因为该类是sealed
。如果我从基类base
派生,是否有任何方法可以“欺骗”并将此
引用重定向到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?
}
}
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...
...
}
}
}
编辑根据请求,以下是上下文:我正在将一个广泛使用
System.Drawing.Bitmap
的.NET类库移植到Windows应用商店库。我解决Windows应用商店中缺少System.Drawing.Bitmap
类的主要想法是实现一个虚拟Bitmap
类,该类将从WriteableBitmap
继承,从而能够返回Windows应用商店类型的位图对象。不幸的是,WriteableBitmap
是密封的
。它的基类BitmapSource
(当然)不是密封的,但另一方面,实际上没有提供任何操作图像的方法。因此我进退两难
大概是这样的:
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?
}
}
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...
...
}
}
}
理想情况下,我希望我的伪
位图
代表Windows应用商店类型的位图类型,这样我就可以将我的伪位图
类分配给一个图像。Source
作为答案添加,这样我就可以提供代码示例,但可以随意作为注释。如果您觉得必须保持这种模式,那么隐式类型转换可能会对您有所帮助。在不知道图像库在做什么的情况下,这只会将问题推向更深层次,因为任何图形。无论采用何种方法,FromImage
都无法工作。如果您的库仅限于GetPixel
、SetPixel
和LockBits
,则您可能需要付出足够的努力才能完成这项工作
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;
}
}
不,那不行。你可以用构图来代替,但我们不能确定。你为什么不告诉我们你要解决的更大的问题,我们也许能提供更多的帮助。约翰说的。此外,根据您试图实现的目标,扩展方法可能是一种选择。继承我认为在这里不是正确的选择,因为jon说,请尝试解释更多,也许我们将为您提供正确的设计模式,例如,尝试查看无有用的注释:)谢谢,@JonSkeet和其他人花时间回应。我已经用一些背景知识更新了这个问题。谢谢,大卫!事实上,我正开始尝试与您上面描述的相同的方法。我意识到内部运作将带来新的挑战,但我会一步一步地进行:-)我会测试这一点,如果它起作用,我会欣然接受答案。