0

我有一个要从命令提示符运行的工具。

代码如下

    static void Main(string[] args)
    {

        string User;            
        if (args[0].Length  != 0)
        {
             User = args[0];
        }
        else
        {
        Console.Write("Please Enter the Username");
        User = Console.ReadLine();
        }

如果我在命令提示符下没有在我的“tool.exe”之后给出用户名或第一个参数,它会抛出一个异常,如“索引超出数组范围”

我想要输出,如果我没有给出论点 - 它应该提示我给出用户名。请帮帮我。

4

7 回答 7

3

args是一个数组,是你应该检查的长度。当您检查时,args[0].Length您实际上假设数组中已经至少有一个元素,因此您正在检查Length第一项。

尝试

if (args.Length != 0)

相反,它检查命令行参数数组的长度。

于 2012-09-18T10:48:59.687 回答
2

您不想调用Length该项目。

            \/ Change here
     if (args.Length  != 0)
    {
         User = args[0];
    }
    else
    {
    Console.Write("Please Enter the Username");
    User = Console.ReadLine();
    }
于 2012-09-18T10:48:33.157 回答
1

您需要将 if 更改为:

static void Main(string[] args)
{

    string User;            
    if (args.Length  != 0) // Change from args[0] to args
    {
         User = args[0];
    }
    else
    {
    Console.Write("Please Enter the Username");
    User = Console.ReadLine();
    }
}

在这个电话之后,确保你在 string.IsNullOrEmpty(User) 使用它之前做了一个。

于 2012-09-18T10:49:27.633 回答
1

做这个

static void Main(string[] args)
{

string User;            
if (args.Length > 0)
{
     User = args[0];
}
else
{
Console.Write("Please Enter the Username");
User = Console.ReadLine();
}
}
于 2012-09-18T10:50:47.067 回答
0

您必须检查参数数组的长度,即参数的数量。目前您正在检查 args[0] 的大小。

if (args.Length  != 0)
{
  // command have some params
}
else
{
 // command have no params
}
于 2012-09-18T10:50:31.747 回答
0

只需替换以下行:

if (args[0].Length != 0)

使用以下代码:

if(arg.Length !=0) <br>

在您的代码中,您在 args 数组中引用了项目 0,然后检查其长度。
由于要检查数组长度,请使用数组本身的 Length 属性

于 2012-09-18T10:54:37.800 回答
0

通过这样做,您正在查看集合 string[] 中的第一个元素。

if (args[0].Length  != 0)

如果没有任何参数,这将给出一个例外。如果要检查是否有任何参数,正确的语句如下。

if (args.Length  != 0)
//Or this
if (args.Any())

注意 Any() 是命名空间 System.Linq 的一部分。

于 2012-09-18T10:59:07.917 回答