Jac*_*cob 2 c# methods function
有没有办法Main()从另一个方法“手动” 调用?我有以下代码:
static void Main(string[] args) {
# some code
function();
}
static void function() {
#some code
Main(); # Start again
}
Run Code Online (Sandbox Code Playgroud)
例如,我有一个简单的控制台计算器,当我在中计算和打印结果时function(),我想以Main()方法中的“输入两个数字:”重新开始。
您还必须添加参数。如果您在主函数中不使用该参数,则可能需要:
null定参数null作为参数
这样工作:
static void code()
{
Main(null);
}
Run Code Online (Sandbox Code Playgroud)
可选属性
然后,您必须像这样修改参数:
static void Main (string[] args = null)
//...
Run Code Online (Sandbox Code Playgroud)
您不能在Main函数中删除该参数,因为它是由其他东西调用的,您不想进行修改。
如果您确实在主函数中使用了args参数,则null可能不是一个好主意,那么您应该使用类似new string[0]以下内容的方法替换它:
static void code()
{
Main(new string[0]);
}
Run Code Online (Sandbox Code Playgroud)
但是,这作为可选参数无效,因为可选参数必须是编译时常量。
如果与它一起使用,则不检查之前的值null就可以得到NullReference异常null。这可以通过两种方式完成:
一,如果条件是这样的:
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();
}
Run Code Online (Sandbox Code Playgroud)
空传播是这样的:
static void Main(string[] args = null)
{
Console.WriteLine("Do something with the arguments. The first item is: " + (args?.FirstOrDefault() ?? "unknown"));
code();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您在Main()通话后忘记了分号。
在调用code方法内部的main方法和代码方法内部的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();
}
Run Code Online (Sandbox Code Playgroud)
在这里您可以获得有关方法的更多信息。但是由于这是通常在学习如何编码的一开始就出现的问题,因此您可能应该阅读像这样的教程。