如何从控制台应用程序返回List <string>?

Ale*_*lex 2 c# program-entry-point console-application

我从Windows窗体应用程序调用控制台应用程序.我想从控制台应用程序中获取一个字符串列表.这是我的简化代码......

[STAThread]
static List<string> Main(string[] args)
{      
    List<string> returnValues = new List<string>();
    returnValues.Add("str_1");
    returnValues.Add("str_2");
    returnValues.Add("str_3");

    return returnValues;
}
Run Code Online (Sandbox Code Playgroud)

BWA*_*BWA 6

这样你就不能。Main 只能返回 void 或 int。但是您可以将列表发送到标准输出并在另一个应用程序中读取它。

在控制台应用程序中添加以下内容:

Console.WriteLine(JsonConvert.SerializeObject(returnValues));
Run Code Online (Sandbox Code Playgroud)

在来电应用程序中:

Process yourApp= new Process();
yourApp.StartInfo.FileName = "exe file";
yourApp.StartInfo.Arguments = "params";
yourApp.StartInfo.UseShellExecute = false;
yourApp.StartInfo.RedirectStandardOutput = true;
yourApp.Start();    

string output = yourApp.StandardOutput.ReadToEnd();
List<string> list = JsonConvert.DeserializeObject<List<string>>(output);

yourApp.WaitForExit();
Run Code Online (Sandbox Code Playgroud)


Pat*_*man 5

你不能只返回一个列表,你必须以另一端可以获取它的方式序列化它.

一种选择是将列表序列化为JSON并通过Console.Out流发送它.然后,在另一端,从进程的输出流中读取并反序列化它.