我目前正在开发一个项目,该项目正在创建一个快速翻译程序来使用Google的API弄乱文本。但是我一直遇到CS0168警告,但不知道如何解决。代码在这里:
using System;
using Google.Cloud.Translation.V2;
namespace Program
{
public partial class Translate
{
[STAThread]
private static void Main()
{
Console.WriteLine("Write text to become cursed");
string Phrase = Console.ReadLine();
string TranslateText() //this variable is the problem
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: Phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
Phrase = response.TranslatedText;
//end of reapeat
return response.TranslatedText;
}
}
}
}
即使我忽略警告,程序也不会运行。
答案 0 :(得分:1)
您的代码有两个主要问题:
正如其他人指出的那样,您声明了局部函数,但从未使用过。
该应用程序已完成所有工作,因此立即退出。您需要在末尾添加Console.ReadLine();
或Console.ReadKey();
,以防止其关闭。
尝试这样的事情:
static void Main(string[] args)
{
Console.WriteLine("Write text to become cursed");
string Phrase = Console.ReadLine();
string TranslateText()
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: Phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
Phrase = response.TranslatedText;
//end of reapeat
return response.TranslatedText;
}
string translatedText = TranslateText();
Console.WriteLine("The translated text is: " + translatedText);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
话虽如此,局部函数可能不是处理此问题的最佳方法。相反,您可以将其移至Main
之外并向其添加一个字符串参数,以便可以将该短语作为参数传递给它。在这种情况下,您的代码将如下所示:
static void Main(string[] args)
{
Console.WriteLine("Write text to become cursed");
string phrase = Console.ReadLine();
string translatedText = TranslateText(phrase);
Console.WriteLine("The translated text is: " + translatedText);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
static string TranslateText(string phrase)
{
TranslationClient client = TranslationClient.Create();
//this block repeats with the language changing each time
var response = client.TranslateText(
text: phrase,
targetLanguage: "language",
sourceLanguage: "language");
Console.WriteLine(response.TranslatedText);
//end of reapeat
return response.TranslatedText;
}