我在嘗試多載新的 .NET 6 C# 控制臺應用程式模板(頂級陳述句)Print(object)中的函式時遇到錯誤。
void Print(object obj) => Print(obj, ConsoleColor.White);
void Print(object obj, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(obj);
Console.ResetColor();
}
錯誤是:
- 從
Print(obj, ConsoleColor.White)->No overload for method Print() that takes 2 arguments - 從
Print(object obj, ConsoleColor color)->A local variable or function named 'Print' is already defined in this scope
我試圖改變他們的順序,但它仍然拋出錯誤。這是怎么回事?
uj5u.com熱心網友回復:
頂層的內容被假定為 的內部Main,因此您在內部宣告了兩個本地函式Main。并且本地函式不支持多載。
你可以:
切換到具有完整類規范的舊樣式模板
class Program { static void Main(){} void Print(object obj) => Print(obj, ConsoleColor.White); void Print(object obj, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(obj); Console.ResetColor(); } }保留新模板,但將您的函式包裝到單獨的類中
var c = new C(); c.Print("test"); public class C{ public void Print(object obj) => Print(obj, ConsoleColor.White); void Print(object obj, ConsoleColor color) { Console.ForegroundColor = color; Console.WriteLine(obj); Console.ResetColor(); }}
與一些技術細節相關的 github isse:https ://github.com/dotnet/docs/issues/28231
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/473350.html
下一篇:.NETCore應用程式和System.Reflection.Assembly.LoadFrom(...)是否存在特定問題?
