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

17

本文介绍了C# 错误:使用未分配的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我不确定为什么会出现这个错误,但这段代码不应该编译吗,因为我已经在检查队列是否正在初始化?

I'm not sure why I'm getting this error, but shouldn't this code compile, since I'm already checking to see if queue is getting initialized?

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

So if queue is not initialized, then the for loops aren't reachable right? Since the program already terminates with Environment.Exit(0)?

希望各位大神指点一下:)

Hope ya'll can give me some pointers :)

谢谢.

推荐答案

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

The compiler doesn't know that the Environment.Exit() is going to terminate the program; it just sees you executing a static method on a class. Just initialize queue to null when you declare it.

Queue queue = null;

这篇关于C# 错误:使用未分配的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14