且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我不能有实例成员在一个静态类,但我能有实例成员的静态方法?

更新时间:2022-10-29 13:45:08

静态方法和属性不能访问非静态字段和事件在其包含的类型,而不能访问任何对象的实例变量,除非它被明确地传递方法参数。

 公共类MyStaticClass
{
    静态诠释J; //静态成员
    INT I; //实例成员
    静态无效MyStaticMethod()
    {
        I = 0; //你不能访问
        J = 0; //你可以访问
    }
}
 

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;
        }
    }

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 
    }
}