简体   繁体   中英

An object reference is required for the non-static field, method, or property

I am getting the following compiler errors with the below code snippet:

An object reference is required for the non-static field, method, or property

in line 5, and

A field initializer cannot reference the non-static field, method, or property

in line 1 here at checker in ThreadStart :

public Thread tC = new Thread(new ThreadStart(checker));

public static void checker()
{
    if (CheckServerState()) LabelWrite(true, Label1);
    else LabelWrite(false,Label1);
}

Could anyone please explain why I get those errors?

In your first code snippet I presume that Label1 is the name of a class, not the name of a variable. You need to instantiate an object of that class. Then you can pass that object to your LabelWrite() method

public static void checker()
{
    Label1 label = new Label1();
    if (CheckServerState()) LabelWrite(true, label);
    else LabelWrite(false,label);
}

The second compiler error means that you can't reference to the method checker() when you are assigning the new Thread object to tC in a field initializer.

You need to do that in a constructor:

public Thread tC;

public MyClass()
{
    tC = new Thread(new ThreadStart(checker));

}

public void checker()
{
    if (CheckServerState()) LabelWrite(true, Label1);
    else LabelWrite(false,Label1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM