首页 > 解决方案 > c# ERROR : 修饰符 'private' 对此项目无效

问题描述

不管我在函数前面放什么修饰符(我尝试过公共、私有甚至受保护),我总是收到一个错误,同样的错误。只有在我删除修饰符并且我没有留下函数“Array()”之后,代码才是干净的。有人可以看看我的代码并向我解释发生了什么吗,我是 C# 的新手,也是寻求帮助的新手,所以请原谅我到目前为止所犯的每一个错误。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {

            public void Array()//nu se pune in interiorul functiei void Main (), deoarece va forma nesting, si ne va da eroare la compilare.
            {
                int[] intArray;
                intArray = new int[3];//all values will be 3


                var doubleArray = new[] { 34.23, 10.2, 23.2 };

                //var arrayElement = doubleArray[0];
                //doubleArray[1] = 5.55;

                for (var i = 0; i < intArray.Length; i++)
                {
                    Console.WriteLine(intArray[i]);
                }
            }

        }



    }
}

我已经在下面发布了代码和它的图像。

在此图像中,您可以看到代码

标签: c#access-modifiersc#-7.0local-functions

解决方案


您有一个嵌套函数,在 C# 中,这些函数称为局部函数并且没有作用域。所以你需要删除访问修饰符,例如:

public static void PrintHelloWorld()
{
    string GetName()
    {
        return "world";
    }


    Console.WriteLine($"Hello {GetName()}");
}

推荐阅读