为什么会出现使用未分配的局部变量?

时间:2015-06-30 16:34:40

标签: c#

这里有许多类似的问题,但我无法理解为什么我不能在C#中使用它们,而在其他语言中使用它们。如果我没有使用try catch块,那么这段代码如何工作,但是我希望在使用它时初始化变量。在这种情况下如何进行内存分配。 附:我是初学者,其中一些对我来说是有限的。

using System;

public class Example
{
   public static void Main()
    {
    int user=0, pass=0;
    do
    {
        Console.WriteLine("Enter the username");
        try
        {
            user = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter the password");
            pass = Convert.ToInt32(Console.ReadLine());
            if (user == 12 && pass == 1234)
                Console.WriteLine("Correct");
            else
                Console.WriteLine("Invalid Username or Password");
            Console.ReadKey();
        }
        catch (FormatException)
        {
            Console.WriteLine("Invalid Format");
        }
        catch (OverflowException)
        {
            Console.WriteLine("Overflow");
        }

    }
    while (user != 12 && pass != 1234);

}



    }

2 个答案:

答案 0 :(得分:4)

在C#中,需要在访问变量之前初始化变量。在您的示例中,如果您没有尝试/捕获阻止,变量userpass将使用

进行初始化
    user = Convert.ToInt32(Console.ReadLine());

    pass = Convert.ToInt32(Console.ReadLine());

在您使用

访问它们的行之前
    while (user != 12 && pass != 1234);

但是,如果你使用try / catch块,就像你的例子一样,并且FormatExceptionOverflowException被抛出

    Convert.ToInt32(Console.ReadLine());

然后在

中访问变量后,变量将被取消初始化
    while (user != 12 && pass != 1234);

答案 1 :(得分:0)

因为如果你在try / catch之前没有初始化变量。你必须在每个块中指定它们

        int user, pass;
        do
        {
            Console.WriteLine("Enter the username");
            try
            {
                user = Convert.ToInt32(Console.ReadLine());// it will not be initialized if process fails.
                pass = Convert.ToInt32(Console.ReadLine());// it will not be initialized if process fails.
            }
            catch (FormatException)
            {
                // what is user and pass?
                Console.WriteLine("Invalid Format");
            }
            catch (OverflowException)
            {
                // what is user and pass?
                Console.WriteLine("Overflow");
            }

        } while (user != 12 && pass != 1234);

因为每个街区都有可能失败。所以你必须在每个块中初始化它们如果你在尝试catch之前不这样做。

如果你不使用try catch:

        int user, pass;
        do
        {
            Console.WriteLine("Enter the username");
            user = Convert.ToInt32(Console.ReadLine()); // it will be initialized any way.
            pass = Convert.ToInt32(Console.ReadLine()); // it will be initialized any way.


        } while (user != 12 && pass != 1234);

Convert.ToInt32(Console.ReadLine());那么用户或传递的价值是什么?

相关问题