【问题标题】:An object reference is required for the non-static field, method, or property 'WindowsFormsApplication1.Main.toolStripStatusLabel1'非静态字段、方法或属性“WindowsFormsApplication1.Main.toolStripStatusLabel1”需要对象引用
【发布时间】:2013-11-29 06:13:15
【问题描述】:

我正在尝试通过静态方法设置toolStripStatusLabel

public static void loggedChanged()
{
    if (SM_Class.logged)
        toolStripStatusLabel1.Text = "Conectado: " + SM_Class.logged_user.username;
    else
    {
        toolStripStatusLabel1.Text = "Desconectado";
    }
}

这来自于类中的另一个静态声明

public static Boolean logged
{
    get { return _logged; }
    set
    {
        if (_logged != value)
        {
            _logged = value;
            Main.loggedChanged();
        }
    }
}

我得到错误:

非静态字段、方法或属性“WindowsFormsApplication1.Main.toolStripStatusLabel1”需要对象引用

我应该改变什么才能更新toolstriplabel?提前致谢。

【问题讨论】:

  • 您的toolStripStatusLabel1 也应该是静态的。
  • 谢谢。但是我应该在哪里将 toolstripStatusLabel1 声明为静态?现在声明如下: private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;
  • 静态初始化在一些实例字段之前运行。这就是为什么您可能会清除此异常。因此,请确保 toolStripStatusLabel1 在使用前已初始化
  • 如果我添加此声明,我不会收到错误:ToolStripStatusLabel toolStripStatusLabel1 = new ToolStripStatusLabel(); - 但不显示工具条状态标签。

标签: c# object methods static


【解决方案1】:

您只给出了部分代码,但看起来问题在于loggedChanged 是静态的,而toolStripStatusLabel1 不是。要么使后者成为静态的,要么使前者成为非静态的。我建议将 loggedloggedChanged 都设为非静态,因为没有充分理由将事物设为静态是不好的做法。

【讨论】:

  • 非常感谢。我从他们两个中删除了静态声明,现在它工作正常。
【解决方案2】:

您不能从静态方法访问非静态内容,除非您将其作为参数传递。

class MyClass{
   String nonstaticField;
   static String staticField;

   static Foo(String obj){
      nonstaticField.Trim(); // no
      staticField.Trim()     // yes
      obj.Trim();            // yes
    }
}

所以你toolStripStatusLabel1 也必须是静态的。在不了解更多信息的情况下,拥有它的最佳位置就是作为现在同一个类中的静态字段。

【讨论】:

  • 非常感谢。我从他们两个中删除了静态声明,现在它工作正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多