您还必须添加参数。如果你不在你的主要功能中使用参数,你有可能:
- 给
null作为参数
- 使参数可选
null 作为参数
这会像这样工作:
static void code()
{
Main(null);
}
可选属性
那么你必须像这样修改参数:
static void Main (string[] args = null)
//...
你不能删除Main函数中的参数,因为它被其他东西调用了,你不想修改。
如果你确实在 main 函数中使用了 args 参数,null 可能不是一个好主意,那么你应该将它替换为类似new string[0]:
static void code()
{
Main(new string[0]);
}
但是,这作为可选参数无效,因为可选参数必须是编译时常量。
如果您将它与null 一起使用,如果您之前未检查null 的值而使用它,您可能会得到一个NullReference 异常。这可以通过两种方式完成:
- 使用 if 条件
- 空传播
if 条件如下所示:
static void Main (string[] args = null)
{
Console.Write("Do something with the arguments. The first item is: ");
if(args != null)
{
Console.WriteLine(args.FirstOrDefault());
}
else
{
Console.WriteLine("unknown");
}
code();
}
Null 传播像这样:
static void Main(string[] args = null)
{
Console.WriteLine("Do something with the arguments. The first item is: " + (args?.FirstOrDefault() ?? "unknown"));
code();
}
顺便说一句,您在Main() 调用后忘记了分号。
也许你应该重新考虑你的代码设计,因为你在 main 方法内调用 code 方法和在 code 方法内调用 main 方法,这可能会导致无限循环,从而导致 StackOverflow例外。您可以考虑将要从 code 方法执行的代码放入另一个方法中,然后在 main 方法和 code 方法中调用该方法:
static void Initialize()
{
//Do the stuff you want to have in both main and code
}
static void Main (string[] args)
{
Initialize();
code();
}
static void code()
{
if (condition /*you said there'd be some if statement*/)
Initialize();
}
Here你可以得到更多关于方法的信息。但由于这通常是在学习如何编码时出现的问题,您可能应该阅读类似this 的教程。