當我宣告該函式時,出現以下錯誤“修飾符‘public’對該專案無效 [c# 類]”。這是我的代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace c__class
{
class Program
{
static void Main(string[] args)
{
string meow = "meow";
public static void sayMeow (ref string purr) { //gets an error
purr = "meow meow";
Console.WriteLine("purr");
}
sayMeow(ref meow);
Console.WriteLine(meow);
}
}
}
當我洗掉它的 public 關鍵字時,有人能告訴我為什么嗎?
uj5u.com熱心網友回復:
您在方法中宣告了一個函式。內部函式不允許有訪問修飾符:
“與方法定義不同,本地函式定義不能包含成員訪問修飾符。因為所有本地函式都是私有的,包括訪問修飾符,例如 private 關鍵字,會生成編譯器錯誤 CS0106,”修飾符 'private' 對以下情況無效這個專案。”
洗掉修飾符或將函式移到方法之外。
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions
uj5u.com熱心網友回復:
由于區域函式對于方法來說是隱式私有的,因此不需要使用成員訪問修飾符顯式宣告。
因為本地函式是嵌套在另一個成員中的型別的私有方法。它們只能從它們的包含成員中呼叫。
官方檔案在這里。
uj5u.com熱心網友回復:
是的,因為您將其宣告為 Main 的本地函式,并且本地函式的唯一可用修飾符是 async、unsafe、static 或 extern。請參閱檔案:https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/local-functions#local-function-syntax
考慮將其宣告為 Program 類的方法成員,在 Main 方法的范圍之外。
uj5u.com熱心網友回復:
您正在另一個函式(Main)中定義該函式。其他函式中的函式不能是公共的或類似的東西。你想要做的是在 Main 函式之外 delcare sayMeow 。當我們在做的時候......你不想使用 ref 關鍵字。它有一些用途。但是在 99.9% 的情況下您不需要它。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace c__class
{
class Program
{
public static void sayMeow (string purr) {
//purr = "meow meow";
Console.WriteLine("purr");
}
static void Main(string[] args)
{
string meow = "meow";
sayMeow(meow);
//Console.WriteLine(meow);
}
}
}
uj5u.com熱心網友回復:
不能有一個方法駐留在方法中。只需將你的 sayMeow 移到 Main() 之外
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/325961.html
上一篇:使用vscode開發一個flutterapp,但是在手機上停止除錯打開app后,卻加載了之前的版本
下一篇:用于分組操作的VSCAPI
