简体   繁体   English

为什么我要使用form1扩展方法必须在非泛型静态类中定义?

[英]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 错误1必须在非泛型静态类中定义扩展方法

This is how the form1 top declared: 这是form1 top声明的方式:

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: 我在form1构造函数中使用此变量:

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

The method ConvertTo24: 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: 和方法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 如果我改变任何东西不是静态的,我在方法ToStream上遇到错误:错误1扩展方法必须是静态的

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. 我尝试做什么静态获取Form1上的错误,当它不是静态我在ToStream上收到错误所以它必须是静态方法。

Because you're using the this keyword as first parameter in ToStream : 因为您在ToStream使用this关键字作为第一个参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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