我看到我可以写:
protected static
Run Code Online (Sandbox Code Playgroud)
在我的C#类中(在我的例子中,是一个aspx.cs).以及 :
private static
Run Code Online (Sandbox Code Playgroud)
这是什么意思?静态随处可见.为什么保护/私人?
如果将变量声明为 Private,则无法在当前类之外访问它,如果声明为 Protected,则只有派生类能够访问该变量。在您的示例中,private 和 Protected 的基本含义是没有改变,所以你如何声明它静态或简单的并不重要......
class Test
{
protected static int var1;
private static int var2;
}
class MainProgram : Test
{
private static int test;
static void Main(string[] args)
{
Test.var1 = 2;
Test.var2 = 5; //ERROR :: We are not able to access var2 because it is private
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,您可以看到如果我们希望静态变量只能在当前类中访问,那么您需要将其设置为 Private。