开发者

Are variables in the main methods static

开发者 https://www.devze.com 2022-12-26 21:01 出处:网络
Its a well known fact that a static method can work only on static members. public static void Main() {

Its a well known fact that a static method can work only on static members.

public static void Main()
{
  开发者_如何学编程  Test t1 = new Test();
}

Here the Main method is static, but I haven't declared t1 as static. Is it implicitly static?


No, it's a local variable. Local variables behave the same way whether they're declared in static methods or instance methods.

As a very rough guide (captured variables etc introduce complications):

  • Instance variables: one variable per instance
  • Static variables: one variable for the type itself
  • Local variables (including parameters): one separate variable for each method call


Its a well known fact that a static method can work only on static members

This is not a fact; this is a falsehood. There is no restriction whatsoever; static methods have full access to all members of their type:

class C 
{
    private int x;
    static C Factory()
    {
        C c = new C();
        c.x = 123;
    }
}

Factory is a static method; it has access to the private instance members of any instance of C.

0

精彩评论

暂无评论...
验证码 换一张
取 消