Do variables in static methods become static automatically because they are within static scopes in c#?

后端 未结 7 1037
长情又很酷
长情又很酷 2021-01-17 17:29
public static void DoSomething()
{
int a;
string b;

//..do something
}

In the example above, i have declared two variables. Do they become static

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-17 18:08

    No, only the method is static.

    From MSDN:

    C# does not support static local variables (variables that are declared in method scope).

    And here:

    The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.

    As you can see, local variables are not mentioned.

    You can, however use a static field:

    public class MyClass
    {
        private static int MyVariable = 10;
    
        public static void MyMethod()
        {
          MyVariable++;
        }
    }
    

    A class can be static, and it can have static members, both functions and fields but not the variables in the static scope.

提交回复
热议问题