【问题标题】:C# Function Overloading in the New .NET 6 Console Template is Not Working新的 .NET 6 控制台模板中的 C# 函数重载不起作用
【发布时间】:2023-01-25 17:24:21
【问题描述】:

我在尝试重载 new .NET 6 C# console app template(顶级语句)中的函数 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

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

【问题讨论】:

    标签: c# .net visual-studio console


    【解决方案1】:

    顶层的内容被假定为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

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多