简体   繁体   中英

How can you extend the Bitmap class

I am trying to extend the Bitmap class so that I can apply my own effects to an image. When I use this code:

namespace ImageEditor
{
    public class Effects : System.Drawing.Bitmap

    {
        public void toBlackAndWhite()
        {
            System.Drawing.Bitmap image = (Bitmap)this;
            AForge.Imaging.Filters.Grayscale filter = new AForge.Imaging.Filters.Grayscale();
            this = filter.Apply(this);
        }
    }
}

I get the following error:

'ImageEditor.Effects': cannot derive from sealed type 'System.Drawing.Bitmap'

So is there a way to get around this or is it simply not possible to extend the class?

Thanks.

You can't derive from Bitmap because it's sealed.

If you want to add a method to the Bitmap class, write an extension method:

// Class containing our Bitmap extension methods.
public static class BitmapExtension
{
    public static void ToBlackAndWhite(this Bitmap bitmap)
    {
        ...
    }
}

Then use it like this:

Bitmap bitmap = ...;
bitmap.ToBlackAndWhite();

+1 for Judah's answer.

Also, consider returning a new bitmap with the filter applied rather than modifying the original. This will give your app more options in the long run (undo etc)

你可以扩展BitmapSource类,如果你转移到WPF并添加一个toblackandwhite方法很容易 - 但是必须使用WPF来读取位图。请参阅自定义BitmapSource

A sealed class means that the author has explicitly dictated that no classes may inherit from it. There's really no way around it. If you're looking to add functions to the Bitmap class, you could look at extension methods .

Of course you could write a wrapper class or a utility class, but extension methods will give you the behavior most like inheriting from Bitmap .

The previous answers are good - extension methods apply nicely here. Also, my first thought was that inheritance isn't a great choice to begin with, since you're not really creating a different kind of bitmap (is-a relationship), you just want to package up some code to manipulate one. In other words there's no need to pass a bitmap-derived class to something, you can just pass the modified bitmap in place of the original.

If you really were intending to override some of Bitmap's methods with your own, I would look carefully again at what you're trying to accomplish - for something as complex as image manipulation you might be better served by supplying functionality alongside the original methods as opposed to superseding them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM