首页 > 解决方案 > 我们如何将字符串从一个方法返回到主方法?

问题描述

我正在尝试PrintBannermain. 但是,它不会让我。

static void Main(string[] args)
{
    string banner;
    banner = PrintBanner("This is whats supposed to be printed."); 
}

public static void PrintBanner()
{
    return PrintBanner(banner); 
}

我需要从 main 调用消息。但是错误表明没有重载 forPrintBanner需要一个参数。并且该名称banner不存在于PrintBanner.

我应该string banner输入PrintBanner方法吗?

标签: c#methods

解决方案


我不清楚你想在这里完成什么。尽管您的代码似乎希望使用 PrintBanner 方法打印并分配一个值。

public static void Main(string[] args)
{
    string banner;
    banner = PrintBanner("This is whats supposed to be printed.");
}
public static string PrintBanner(string text)
{
    Console.Write(text);
    return text;
}

或者您可能不希望方法本身执行分配?:

public static void Main(string[] args)
{
    string banner;
    PrintBanner(banner = "This is whats supposed to be printed.");
}
public static void PrintBanner(string text)
{
    // The text variable contains "This is whats supposed to be printed." now.
    // You can perform whatever operations you want with it within this scope,
    // but it won't alter the text the banner variable contains.
}

如果不是,请尝试进一步详细说明您的目标。


推荐阅读