避免System.IndexOutOfRangeException - 使用main方法args [英] Avoid the System.IndexOutOfRangeException - with main method args

查看:68
本文介绍了避免System.IndexOutOfRangeException - 使用main方法args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

所以我对C#还不熟悉,而我正在尝试做的是构建一个app,当exe为2时需要2个args执行。

So I'm fairly new to C# and what I'm trying to do is to build out an app that takes 2 args when the exe is executed.

但是,如果用户不提供其中一个或两个参数,我会调用一个方法来询问数据。

However, if the user does not supply one or both of those arguments, that I call a method to ask for the data.

她是我正在考虑的代码,但当然,当我运行它时,我得到预期的超出范围异常。

Her's the code that I'm thinking about, but of course when I run it, I get the expected out of range exception.

我想知道这样的事情是否可行:

I'm wondering if something like this is possible:

static void Main(string[] args)
{
	if (args.Length < 1)
	{
		GetAndSetVueValues();
	}
	else
	{
		if (!string.IsNullOrEmpty(args[0]))
	{

		//call the method to ask the user for the missing args
	}

... rest of the code


谢谢!

Thanks!

推荐答案

也许从这开始:

Maybe start with this:

string arg1, arg2;

switch( args.Length )
{
case 0:
    Console.WriteLine( "Please enter two arguments." );
    Console.Write( "Argument 1: " );
    arg1 = Console.ReadLine();
    Console.Write( "Argument 2: " );
    arg2 = Console.ReadLine();
    break;
case 1:
    arg1 = args[0];
    Console.WriteLine( "Argument 1: {0}", arg1 );
    Console.WriteLine( "Please enter the second argument." );
    Console.Write( "Argument 2: " );
    arg2 = Console.ReadLine();
    break;
case 2:
    arg1 = args[0];
    arg2 = args[1];
    Console.WriteLine( "Argument 1: {0}", arg1 );
    Console.WriteLine( "Argument 2: {0}", arg2 );
    break;
default:
    Console.WriteLine( "Too many arguments." );
    Console.WriteLine( "Please supply no more than two arguments." );
    return;
}

// process 'arg1' and 'arg2'
// . . .

这篇关于避免System.IndexOutOfRangeException - 使用main方法args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆