28

我不确定为什么会收到此错误,但不应该编译此代码,因为我已经在检查队列是否正在初始化?

public static void Main(String[] args)
{
    Byte maxSize;
    Queue queue;

    if(args.Length != 0)
    {
        if(Byte.TryParse(args[0], out maxSize))
            queue = new Queue(){MaxSize = maxSize};
        else
            Environment.Exit(0);
    }
    else
    {
        Environment.Exit(0);
    }

    for(Byte j = 0; j < queue.MaxSize; j++)
        queue.Insert(j);
    for(Byte j = 0; j < queue.MaxSize; j++)
        Console.WriteLine(queue.Remove());
}

因此,如果队列未初始化,那么 for 循环就无法访问,对吗?由于程序已经以 Environment.Exit(0) 终止?

希望你们能给我一些指点:)

谢谢。

4

4 回答 4

75

编译器不知道 Environment.Exit() 将终止程序;它只是看到你在一个类上执行一个静态方法。声明时只需初始化queue为 null 即可。

Queue queue = null;
于 2008-11-01T20:35:29.280 回答
9

编译器不知道 Environment.Exit() 不会返回。为什么不只是从 Main() 中“返回”?

于 2008-11-01T20:35:14.053 回答
8

解决问题的几种不同方法:

只需将 Environment.Exit 替换为 return。编译器知道 return 结束了方法,但不知道 Environment.Exit 会结束。

static void Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return;
    } else {
       return;   
}

当然,你真的只能侥幸逃脱,因为在所有情况下你都使用 0 作为退出代码。确实,您应该返回一个 int 而不是使用 Environment.Exit。对于这种特殊情况,这将是我的首选方法

static int Main(string[] args) {
    if(args.Length != 0) {
       if(Byte.TryParse(args[0], out maxSize))
         queue = new Queue(){MaxSize = maxSize};
       else
         return 1;
    } else {
       return 2;
    }
}

将队列初始化为 null,这实际上只是一个编译器技巧,上面写着“我会找出我自己的未初始化变量,非常感谢”。这是一个有用的技巧,但在这种情况下我不喜欢它 - 你有太多的 if 分支来轻松检查你是否正确地执行它。如果你真的想这样做,这样的事情会更清楚:

static void Main(string[] args) {
  Byte maxSize;
  Queue queue = null;

  if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
     Environment.Exit(0);
  }
  queue = new Queue(){MaxSize = maxSize};

  for(Byte j = 0; j < queue.MaxSize; j++)
    queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
    Console.WriteLine(queue.Remove());
}

在 Environment.Exit 之后添加一个 return 语句。同样,这更像是一个编译器技巧 - 但在 IMO 中稍微合法一些,因为它也为人类添加了语义(尽管它会让你远离那个自吹自擂的 100% 代码覆盖率)

static void Main(String[] args) {
  if(args.Length != 0) {
     if(Byte.TryParse(args[0], out maxSize)) {
        queue = new Queue(){MaxSize = maxSize};
     } else {
        Environment.Exit(0);
        return;
     }
  } else { 
     Environment.Exit(0);
     return;
  }

  for(Byte j = 0; j < queue.MaxSize; j++)
     queue.Insert(j);
  for(Byte j = 0; j < queue.MaxSize; j++)
     Console.WriteLine(queue.Remove());
}
于 2008-11-02T01:36:06.130 回答
0

如果您使用“return”,编译器只知道代码是否可以访问。将 Environment.Exit() 视为您调用的函数,编译器不知道它将关闭应用程序。

于 2008-11-01T20:47:18.210 回答