关键字 'this' 在静态属性、静态方法或静态字段初始值设定项中无效


public static void Main()
{
    Stream s1 = this.GetType().Assembly.GetManifestResourceStream("WindowsApplication1.sudhir.jpg");
    Stream s2 = this.GetType().Assembly.GetManifestResourceStream("WindowsApplication1.sunil.jpg");
    Bitmap img1 = new Bitmap(s1);
    Bitmap img2 = new Bitmap(s2);
    if (img1.Size != img2.Size)
    {
        Console.Error.WriteLine("Images are of different sizes");
        return;
    }
    float diff = 0;
    for (int y = 0; y < img1.Height; y++)
    {
        for (int x = 0; x < img1.Width; x++)
        {
            diff += (float)Math.Abs(img1.GetPixel(x, y).R - img2.GetPixel(x, y).R) / 255;
            diff += (float)Math.Abs(img1.GetPixel(x, y).G - img2.GetPixel(x, y).G) / 255;
            diff += (float)Math.Abs(img1.GetPixel(x, y).B - img2.GetPixel(x, y).B) / 255;
        }
    }
    Console.WriteLine("diff: {0} %", 100 * diff / (img1.Width * img1.Height * 3));

这里我试图匹配两个图像并找出它们的差异但是我得到了这个错误

关键字'this'在静态属性、静态方法或静态字段初始化项中无效。

出了什么问题,我怎么解决这个问题?

这个关键字仅在处理对象(即实例)的情况下有效。当你使用静态方法时,这意味着你不处理一个特定的对象,而是处理一个类,因为"this"不指向任何东西。

"this"是一个指向当前类实例的不可见形参。由于将方法声明为静态,因此无法访问它。这不仅存在于c#中。c++也有"this"。

您的main方法是静态的,因此您不能调用this.你可以这样写:

 Stream s1 = Assembly.GetExecutingAssembly().GetManifestResourceStream("WindowsApplication1.sudhir.jpg");

'this'仅在对象上下文中有意义,不能在静态代码中使用。如果在设置字段的起始值时需要引用'this',请在构造函数中设置该值。

错误消息将告诉您哪个文件的哪一行导致了问题。我认为这不是你给我们看的任何一行。

最新更新