【问题标题】:What's the difference between (string[] args) and System.Environment.CommandLine?(string[] args) 和 System.Environment.CommandLine 有什么区别?
【发布时间】:2012-06-17 20:56:58
【问题描述】:

我继承了几个控制台应用程序的维护,这些控制台应用程序自然是使用static void Main(string[] args) 输入的。但是,代码忽略了args 数组,而是从System.Environment.CommandLine 读取命令行参数。

这里有功能上的区别吗?

内容看起来相同。如果有的话,我会怀疑调用 System.Environment.CommandLine 会对性能造成一分钟的影响(但还不足以让我担心或关心到足以衡量)。


更新:我怀疑System.Environment.CommandLine 应该包含可执行路径,但我没有看到它......因为我找错了地方。代码还具有string[] arrCmdLine = System.Environment.GetCommandLineArgs(); .... System.Environment.CommandLine.ToLower() 检查是否存在“调试”,而所有其他参数都是从GetCommandLineArgs() 中提取的,当我打算“为什么不只使用@ 987654329@?”

多年来,我一直在为解析命令行参数的最佳方式而苦恼,而一直以来都是“将它们按正确的顺序排列!” [jk]

【问题讨论】:

    标签: .net parameters command-line-arguments


    【解决方案1】:

    System.Environment.CommandLine 将可执行文件和参数包含为单个字符串。

    // Sample for the Environment.CommandLine property.
    using System;
    
    class Sample 
    {
        public static void Main() 
        {
            Console.WriteLine();
            //  Invoke this sample with an arbitrary set of command line arguments.
            Console.WriteLine("CommandLine: {0}", Environment.CommandLine);
        }
    }
    
    /*
    This example produces the following results:
    
    C:\>env0 ARBITRARY TEXT
    
    CommandLine: env0 ARBITRARY TEXT
    */
    

    http://msdn.microsoft.com/en-us/library/system.environment.commandline.aspx

    args 参数是一个参数数组。因此,虽然您可以解析来自 System.Environment.CommandLine 的各个参数,但我不确定您为什么要这样做。我能看到的唯一原因是您是否需要访问Main() 之外的参数,无论如何这可能是个坏主意。您的 Main() 方法应该处理参数并根据需要将它们传递给应用程序的其余部分。

    【讨论】:

    • 使用 Environment.CommandLine 将 args 拆分为数组的最佳方法是什么?原因是,如果 My.Application.CommandLineArgs 在 arg(s) 中,则不包含引号。即传递了带有字符串的路径,需要用引号引起来。准确查看包含引号的“原始”参数的唯一方法是使用 Environment.CommandLine,但不会将其拆分为数组。
    猜你喜欢
    • 2014-02-22
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2010-09-23
    相关资源
    最近更新 更多