简体   繁体   中英

Why can I not have instance members in a static class but I can have instance members in a static methods?

We know that If a class is made static, all the members inside the class have to be static; there cannot be any instance members inside a static class. If we try to do that, we get a compile time error.

But if have an instance member inside a static method, I do not get a compile time error.

    public static class MyStaticClass
    {
        // cannot do this
        //int i;

        // can do this though.
        static void MyStaticMethod()
        {
            int j;
        }
    }

Its not instance member, its ( j ) a local variable inside a static method.

Consider following non-static class.

public class MyStaticClass
{
    int i; //instance member
    static void MyStaticMethod()
    {
        i = 0; // you can't access that
    }
}

The above class has a instance member i , you can't access that in a static method.

static void MyStaticMethod()
{
   int j;
}

You have a local variable (j) inside your static method.

For your information from MSDN :

You can define a class as static if you want to guarantee that it can't be instantiated, can't derive from or serve as the base for another type, and can contain only static members.

Static members are initialized before the static member is accessed for the first time and before the static constructor, if there is one, is called.

Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.

public class MyStaticClass
{
    static int j; //static member
    int i;//instance member
    static void MyStaticMethod()
    {
        i = 0; // you can't access that
        j = 0; // you can access 
    }
}

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