繁体   English   中英

C#错误:使用未分配的局部变量

[英]C# error: Use of unassigned local variable

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

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)终止?

希望你能给我一些指示:)

谢谢。

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

Queue queue = null;

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

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

只需将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,这实际上只是一个编译器技巧,说“我会弄清楚我自己的未初始化变量,非常感谢你”。 这是一个有用的技巧,但在这种情况下我不喜欢它 - 你有太多的分支,以便轻松检查你是否正确地做到了。 如果你真的想这样做,这样的事情会更清楚:

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());
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM