新的 .NET 6 控制台模板中的 C# 函数重载不起作用

Abd*_*awi 4 .net c# console visual-studio

我在尝试重载新的 .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();
}
Run Code Online (Sandbox Code Playgroud)

错误是:

  • 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

我尝试改变他们的顺序,但仍然抛出错误。这是怎么回事?

Ser*_*erg 10

假定顶层的内容是 的内部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(); 
     }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 保留新模板,但将函数包装到单独的类中

    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(); 
         }
    
    Run Code Online (Sandbox Code Playgroud)

    }

相关的 github isse 包含一些技术细节:https ://github.com/dotnet/docs/issues/28231