我在尝试重载该函数时遇到错误Print(object)
in the 新的 .NET 6 C# 控制台应用程序模板 https://learn.microsoft.com/en-us/dotnet/core/tutorials/top-level-templates(顶层声明)。
void Print(object obj) => Print(obj, ConsoleColor.White);
void Print(object obj, ConsoleColor color)
{
Console.ForegroundColor = color;
Console.WriteLine(obj);
Console.ResetColor();
}
错误是:
- From
Print(obj, ConsoleColor.White)
-> No overload for method Print() that takes 2 arguments
- From
Print(object obj, ConsoleColor color)
-> A local variable or function named 'Print' is already defined in this scope
我尝试改变他们的顺序,但仍然抛出错误。这是怎么回事?
顶层的内容被假定为内部结构Main
,所以你声明了两个local里面的功能Main
。并且局部函数不支持重载。
You can:
-
切换到具有完整类规范的旧样式模板
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://github.com/dotnet/docs/issues/28231
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)