Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 非静态字段、方法或属性需要对象引用';WindowsFormsApplication1.Main.toolStripStatusLabel1';_C#_Object_Methods_Static - Fatal编程技术网

C# 非静态字段、方法或属性需要对象引用';WindowsFormsApplication1.Main.toolStripStatusLabel1';

C# 非静态字段、方法或属性需要对象引用';WindowsFormsApplication1.Main.toolStripStatusLabel1';,c#,object,methods,static,C#,Object,Methods,Static,我正在尝试从静态方法设置toolStripStatusLabel: public static void loggedChanged() { if (SM_Class.logged) toolStripStatusLabel1.Text = "Conectado: " + SM_Class.logged_user.username; else { toolStripStatusLabel1.Text = "Desconectado";

我正在尝试从静态方法设置
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
?提前感谢。

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

除非将其作为参数传递,否则无法从静态方法访问非静态内容

class MyClass{
   String nonstaticField;
   static String staticField;

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

因此,您的
toolStripStatusLabel1
也必须是静态的。在不了解更多信息的情况下,最好将其放在与现在相同的类中的静态字段中。

您的
toolStripStatusLabel1
也应该是静态的。谢谢。但我应该在哪里将toolstripStatusLabel1声明为静态?现在声明如下:private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1;静态初始化在某些实例字段之前运行。这就是为什么您可能会将此异常捕获。因此,在使用ITI之前,请确保toolStripStatusLabel1已初始化。如果我添加此声明,则不会出现错误:ToolStripStatusLabel toolStripStatusLabel1=new ToolStripStatusLabel();-但是toolstripstatuslabel不显示。非常感谢。我从这两个文件中删除了静态声明,现在它工作得很好。非常感谢。我从它们中删除了静态声明,现在它工作得很好。