【问题标题】:C# Use 'this' Keyword in a class [closed]C#在类中使用'this'关键字[关闭]
【发布时间】:2016-06-05 10:18:08
【问题描述】:

我有一个从两点创建 LineShape 的代码。

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;

谢谢!

【问题讨论】:

  • “但什么都没有”是什么意思?在任何情况下,thisstatic 方法中都没有意义——它指向当前对象实例,而静态方法没有当前实例。这是基本的 C#。
  • 关键字static 表示您没有对象的实例。而this 指的是当前实例。从方法声明中删除static
  • 你没有问问题。这是一个问答网站;您的准确问题是什么?
  • 在静态方法中没有“this”,如错误所示。这有什么不清楚的?你明白“静态”和“这个”是什么意思吗?

标签: c# winforms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-10-10
    • 2014-03-30
    • 2018-03-24
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多