C# 在类中使用“this”关键字

本文关键字:this 关键字 | 更新日期: 2023-09-27 18:36:01

我有一个从两个点创建线条形状的代码。

class MyMenu
{
    public static void AddLine()
    {
        ShapeContainer canvas = new ShapeContainer();
        LineShape theLine = new LineShape();
        canvas.Parent = this;
        theLine.Parent = canvas;
        theLine.BorderColor = SystemColors.ControlDarkDark;
        theLine.StartPoint = new System.Drawing.Point(-3, 154);
        theLine.EndPoint = new System.Drawing.Point(212, 154);
    }
}

我想创建一个类并从那里使用,但我最终遇到了一个错误。

Keyword 'this' is not valid in a static property, static method, or static field initializer    

我试图像这样修复它,但什么都没有!

 Form1 MyForm = new Form1();
        canvas.Parent = MyForm;

谢谢 !

C# 在类中使用“this”关键字

我不确定,您可以尝试将表单引用传递到方法中(如果这就是您的意思)。

class MyMenu
{
    public static void AddLine(Form f)
    {
        ShapeContainer canvas = new ShapeContainer();
        LineShape theLine = new LineShape();
        canvas.Parent = f;
        theLine.Parent = canvas;
        theLine.BorderColor = SystemColors.ControlDarkDark;
        theLine.StartPoint = new System.Drawing.Point(-3, 154);
        theLine.EndPoint = new System.Drawing.Point(212, 154);
    }
}

从表格:

MyMenu.AddLine(this);