当我不使用所有参数调用控制台应用程序时,我会得到 System.IndexOutOfRangeException(尽管大多数参数都是可选的)。为什么?

问题描述 投票:0回答:1

我有一个 C# .NET Framework 4.7.2 C# 控制台应用程序,它从远程 OPC DA 服务器读取最多 20 个 OPC DA 项目。我从另一个带参数的 .NET 应用程序调用此控制台应用程序。第一个参数定义应读取的项目数量,其余 20 个项目。 我希望在我称之为控制台应用程序的父应用程序中,我只需编写(除了第一个参数之外)所需数量的参数(对于三个项目,只需 3 个)。但在我当前的代码中,我必须将其余 17 个参数至少定义为 x (尽管未使用),否则我会在控制台应用程序上收到以下错误:

Description: The process was terminated due to an unhandled exception.
Exception Info: System.IndexOutOfRangeException
at CNCOnline_OPC_DA.Program..ctor()
at CNCOnline_OPC_DA.Program.Main(System.String[])

如何防止这种情况发生?我的意思是前 2 个参数应该是强制性的(项目数量,以及至少一个项目),其余 19 个参数是可选的。

家长应用程序:

Process Process_OPCDA = new Process
{
   StartInfo = new ProcessStartInfo
   {
   FileName = TagService_MTX.MTX_OPC_DA_reader_path,
   Arguments = "3 item1 item2 item3 x x x x x x x x x x x x x x x x x"
   UseShellExecute = false,
   RedirectStandardOutput = true,
   CreateNoWindow = true
   }
};
Process_OPCDA.Start();

带参数的控制台应用程序:

    public string item_no = Environment.GetCommandLineArgs()[1];
    public string item_1 = Environment.GetCommandLineArgs()[2];
    public string item_2 = Environment.GetCommandLineArgs()[3];
    public string item_3 = Environment.GetCommandLineArgs()[4];
    //...all 20 defined here
    public string item_20 = Environment.GetCommandLineArgs()[21];

    static void Main(string[] args)
    {
        for(int b=0;b<20;b++)
        {
            if(Environment.GetCommandLineArgs()[b+2].Length > 0) 
            { 
                item_array[b]= Environment.GetCommandLineArgs()[b+11];
            }
            else
            {
                item_array[b] = "";
            }
        }

        // rest code...
    }
c# arguments console-application optional-parameters
1个回答
0
投票

如果您有权访问 Main 方法的

Environment.GetCommandLineArgs()
参数,请不要使用
args
,这只会造成混乱。也不要对给出的参数数量做出假设(或者至少之前检查一下)。我建议你改变你的方法是这样的:

    // .... 
    public string item_20;

    static void Main(string[] args)
    {
        if (args.Count < 20)
        {
            Console.WriteLine("Not enough parameters");
            return;
        }
        item_1 = args[0];
        item_2 = args[1]; // etc... Instead, you could also create a copy of the array and keep the indexing
        for(int b=0;b<18;b++)
        {
            // You might eventually need to consider it an error if 
            // the b + 11 doesn't exist.
            if(args[b+2].Length > 0 && b + 11 < args.Count) 
            { 
                item_array[b]= args[b+11];
            }
            else
            {
                item_array[b] = "";
            }
        }

        // rest code...
    }

您的 for 循环看起来参数的定义方式也存在一些含糊之处。你怎么知道你期望有多少个参数?看起来您的输入字符串确实很复杂,因此请尝试使用带有命名参数的命令行解析库,或者可能更好,使用文件为您的程序提供输入。

© www.soinside.com 2019 - 2024. All rights reserved.