简体   繁体   中英

Why i'm getting on form1 Extension method must be defined in a non-generic static class?

Error 1 Extension method must be defined in a non-generic static class

This is how the form1 top declared:

public partial class Form1 : Form

Then i declared some variable as static:

private static FileInfo newest;
private static Stream mymem;
private static Bitmap ConvertedBmp;
private static Stopwatch sw;

I use this variables in form1 constructor:

ConvertedBmp = ConvertTo24(newest.FullName);
mymem = ToStream(ConvertedBmp, ImageFormat.Bmp);

The method ConvertTo24:

private static Bitmap ConvertTo24(string inputFileName)
        {
            sw = Stopwatch.StartNew();
            Bitmap bmpIn = (Bitmap)Bitmap.FromFile(inputFileName);
            Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
            using (Graphics g = Graphics.FromImage(converted))
            {
                g.PageUnit = GraphicsUnit.Pixel;
                g.DrawImageUnscaled(bmpIn, 0, 0);
            }
            sw.Stop();
            return converted;
        }

And the method ToStream:

public Stream ToStream(this Image image, ImageFormat formaw)
        {
            var stream = new System.IO.MemoryStream();
            image.Save(stream, formaw);
            stream.Position = 0;
            return stream;
        }

If i change anything to be not static i'm getting error on the method ToStream: Error 1 Extension method must be static

I tried to do anything static getting the error on Form1 when it's all not static i'm getting error on ToStream so it must be static method.

Because you're using the this keyword as first parameter in ToStream :

public Stream ToStream(this Image image, ImageFormat formaw)

which is allowed only in extension methods. Remove it.

If you want to use it as extension method (which doesn't seem to be the case), the method must be sitting in a static class like this:

public static class MyDrawingExtensions
{
    public static Stream ToStream(this Image image, ImageFormat formaw)
    {
        // ...
    }
}

Then you could call it (also) in this way:

mymem = ConvertedBmp.ToStream(ImageFormat.Bmp);

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