繁体   English   中英

不能正确获取命令行参数输出

[英]Not Getting the Command Line Parameter Output Properly

我试图显示作为输入输入的命令行参数数。 这是我的代码块。

//Argument: A, B, C, D

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ParamaterCount
{
    public class ParameterCount
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
            Console.WriteLine("You have entered {0} command line arguments",args.Length);
            Console.ReadLine();
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine("{0}", args[i]);
            }
        }
    }
}

但是,当我尝试运行它时。 它从屏幕上消失了,我什么也没得到。 我还添加了Console.ReadLine()语句,但无法在For循环内部输入以计算迭代次数。 我想念什么吗? 谢谢。

输出应该是这样的。

Hello World,
You entered 4 Command Line Arguments
A
B
C
D

在控制台应用程序中,参数将无法那样工作。 您的代码还可以,但是请注意,您必须在运行时输入参数,但是由于在运行时调用的第一个方法是Main()因此您没有机会提供命令行参数。 为了实现所需的功能,必须从命令行运行已编译的输出应用程序,假设您的应用程序名称为ConsoleApplication.exe ,因此请打开命令行,然后按如下所示运行ConsoleApplication.exe

ConsoleApplication.exe A B C …

有关更多信息,请参见: 命令行参数

BTW:你总是可以运行使用CTRL + F5代替F5控制台应用程序,因为如果你写了这将产生相同的结果Console.ReadLine()在你的应用程序的结束。

您应该在Main方法的末尾移动Console.ReadLine()语句。 因此,您的代码应如下所示:

public static void Main(string[] args)
{
    Console.WriteLine("Hello World");
    Console.WriteLine("You have entered {0} command line arguments",args.Length);

    for (int i = 0; i < args.Length; i++)
    {
        Console.WriteLine("{0}", args[i]);
    }
    Console.ReadLine();
}

尝试:

 public static void Main(string[] args)
{
    Console.WriteLine("Hello World");
    Console.WriteLine("You have entered {0} command line arguments {1}",args.Length, string.Join(" ", args);

    Console.ReadLine();
}

从控制台运行程序时,除去console.readline()语句,而是提供输入。 我对c#一无所知,但是在Java中,您可以按以下步骤完成上述任务。

javac s.java
java s A B C D

实际上 ,您不需要使用Console.ReadLine()因为它读取输入流,而不是您提供的参数。

那就是您只需要的代码;

Console.WriteLine("Hello World");
Console.WriteLine("You have entered {0} command line arguments", args.Length);
for(int i = 0; i < args.Length; i++)
{
    Console.WriteLine("{0}", args[i]);
}

然后执行以下步骤;

  • Run并键入cmd.exe ,这是命令行的快捷方式
  • cd转到您的exe文件夹(在我的示例中为cd C:\\Users\\Soner\\Documents\\Visual Studio 2012\\Projects\\ProgramConsole\\ProgramConsole\\bin\\Debug
  • 使用名称和ABCD运行exe(在我的示例ProgramConsole.exe ABCD

输出将是;

Hello World
You have entered 4 command line arguments
A
B
C
D

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM