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

I know that people have asked this question before, but the scenario was too specific, and I am confused about the basic principles.

I have two basic versions of C #, one of which works, and the other does not. I would be very pleased if someone could explain why I get an error. An object reference is required for a non-static field, method or property in the second program.

Works:

namespace Experiments
{
    class Test
    {
        public string myTest = "Gobbledigook";

        public void Print()
        {
            Console.Write(myTest);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test newTest = new Test();
            newTest.Print();
            while (true)
                ;
        }
    }
}

Does not work:

namespace Experiments
{
    class Test
    {
        public string myTest = "Gobbledigook";

        public void Print()
        {
            Console.Write(myTest);
        }
    }

    class Program
    {
        public Test newTest = new Test();

        static void Main(string[] args)
        {
            newTest.Print();
            while (true)
                ;
        }
    }
}

() Test() , , , , . , , Test(), ++, .

?

+3
2

- , static.

newTest Test Program main . An object reference is required for the non-static method. , newTest newTest , main.

 public static Test newTest = new Test();

, Print static Test :

 public static void Print()
 {
    Console.Write(myTest);
 }

, , (newTest.Print();). Test.Print(); , . . ,

+4

static. .

, , . , , , , , !

, newTest , - Program, Program p = new Program();. , static Print(). Min() , Main() .

, e.x. MyGlobals:

public class SomeClass
{
    public int x;
}

public class MyGlobals
{
    public static SomeClass mySharedVariable = new SomeClass();

    public SomeClass myGlobalVariable = null;
}

// Usage:
class Program
{
    static void Main(string[] args)
    {
        MyGlobals.mySharedVariable.x = 10; // Shared among all instances
        MyGlobals myGlobal = new MyGlobals(); // New instance of MyGlobals
        myGlobal.myGlobalVariable = new SomeClass(); // New instance of SomeClass
        myGlobal.myGlobalVariable.x = 10; // One instance of MyGlobals including one instance of SomeClass
    }
}
0

Source: https://habr.com/ru/post/1658279/


All Articles