Cor*_*ina 1 c# access-modifiers c#-7.0 local-functions
我在函数的前面放了什么修饰符都没关系(我尝试过使用public,private甚至protected),但我总是收到一个错误,同样的错误。仅在删除修饰符且函数“ 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]);
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
我将代码及其图像发布在下面。
您有一个嵌套函数,在 C# 中,这些函数被称为本地函数并且没有作用域。所以你需要删除访问修饰符,例如:
public static void PrintHelloWorld()
{
string GetName()
{
return "world";
}
Console.WriteLine($"Hello {GetName()}");
}
Run Code Online (Sandbox Code Playgroud)
您正在创建一个nested method(也称为局部函数)。嵌套方法可能没有访问修饰符。它们只能从此方法中访问。
供参考:https : //docs.microsoft.com/dotnet/csharp/programming-guide/classes-and-structs/local-functions