【问题标题】:Call Main from another method从另一个方法调用 Main
【发布时间】:2017-09-27 15:53:50
【问题描述】:

有没有办法“手动”从另一种方法调用Main()?我有以下代码:

static void Main(string[] args) {
    # some code
    function();
}

static void function() {
    #some code
    Main(); # Start again
}

我有例如简单的控制台计算器,当我计算并在function() 中打印结果时,我想重新开始,例如Main() 方法中的“输入两个数字:”。

【问题讨论】:

  • 当然可以,但是你没有传入任何参数。 但是你会得到一个 StackOverflow 异常,原因是,你在 main 中调用 code(),然后在 code() 中调用 Main不是一个好主意。
  • 请先尝试找一本像样的书或基础编程教程。
  • 这只是一个例子,我的真实代码还不错:D

标签: c# function methods


【解决方案1】:

您还必须添加参数。如果你不在你的主要功能中使用参数,你有可能:

  1. null作为参数
  2. 使参数可选

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 异常。这可以通过两种方式完成:

  1. 使用 if 条件
  2. 空传播

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 的教程。

【讨论】:

  • 你写了static void Main (string[] args = new string[0]),但那个新数组表达式不是一个常量表达式,不能用作可选参数的默认参数。
  • @JeppeStigNielsen 你是对的 - 我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 2016-10-10
  • 1970-01-01
  • 2011-10-07
  • 1970-01-01
相关资源
最近更新 更多