What can I do with a protected/private static variable?

前端 未结 7 2243
悲&欢浪女
悲&欢浪女 2021-01-01 18:00

I see I can write :

protected static

in my C# class (in my case, an aspx.cs). As well as :

private static

7条回答
  •  -上瘾入骨i
    2021-01-01 18:37

    If you declare a variable as a Private then you are not able to access it outside the current class and if declare as a Protected then only the derived class is able to access that variable..In your example the basic meaning of private and Protected is not changing so it does not matter how you declare it Static or simple one...

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

    In above code you can see if we want the static variable is accessible only in the current class then you need to make it as a Private.

提交回复
热议问题