首页 > 解决方案 > 不能使用公共访问修饰符

问题描述

抱歉,如果这是一个非常愚蠢的问题,但我正在胡乱摆弄我从 YouTube 初学者教程中学到的东西,我有点迷路了。谁能让我知道为什么在打破一切public之前使用访问说明符?fields

namespace ConsoleApp1
{
    class Methods
    {



        static void Main(string[] args)
        {
            public int _first, _second, _third, _fourth, _fifth;


        for (int i=1;i<=5;i++)
            {
                Console.WriteLine("Enter {0}st number:", i);
                Console.ReadLine();
                switch (i)
                {
                    case 1:
                        _first = i;
                        break;
                }
            }

        }

使用公共 不使用公共

标签: c#syntax-error

解决方案


问题是范围。

函数范围内的字段(在函数或方法中最好使用变量)不能是“公共”或“受保护”或......不,是容器范围的私有,当然,不需要访问单词。

如果您在函数之外创建一个字段,您可以将其设为公共、私有、内部......等等......

您不能从对象或结构中创建字段。

namespace ConsoleApp1
{

    public int _secondThing // baaaad

    class Methods
    {

        public static int _thing; //good
        int _thing; //good, it's private;
        private int _thing; //good, it's the same
        public int _firstThing; //good

        static void Main(string[] args)
        {
            public int _first, _second, _third, _fourth, _fifth; //baaad
            int _first, _second; //good
        }
    }
}

推荐阅读