繁体   English   中英

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

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

错误1必须在非泛型静态类中定义扩展方法

这是form1 top声明的方式:

public partial class Form1 : Form

然后我将一些变量声明为静态:

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

我在form1构造函数中使用此变量:

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

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

和方法ToStream:

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

如果我改变任何东西不是静态的,我在方法ToStream上遇到错误:错误1扩展方法必须是静态的

我尝试做什么静态获取Form1上的错误,当它不是静态我在ToStream上收到错误所以它必须是静态方法。

因为您在ToStream使用this关键字作为第一个参数:

public Stream ToStream(this Image image, ImageFormat formaw)

只允许在扩展方法中使用。 去掉它。

如果你想将它用作扩展方法 (似乎不是这种情况),那么该方法必须位于如下的静态类中:

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

然后你可以用这种方式调用它(也)

mymem = ConvertedBmp.ToStream(ImageFormat.Bmp);

暂无
暂无

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

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