使用未分配的局部变量错误的原因 [英] Reason for use of unassigned local variable error

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

问题描述

我只是想知道为什么编译器会给我这个错误.每次调用函数时都会执行try块,这意味着将分配该变量.但是仍然不能让我编译.

I'm just wondering why the compiler gives me this error. The try block will be executed every time the function is called and that means the variable will get assigned. But still it doesn't let me compile.

using System;

namespace Checking
{
    class Program
    {
        static void Main(string[] args)
        {
            int intNum;
            intNum = readValue("Please enter a number: ");

        }
        static int readValue(string strPrompt)
        {
            int intRes;
            Console.WriteLine(strPrompt);
            try
            {
                intRes = Convert.ToInt32(Console.ReadLine());   // Gets assigned here! But still doesnt allow me to compile!

            }
            catch (Exception ex)
            {
                Console.WriteLine("Please enter a numeric value.\n");
                readValue(strPrompt);
            }
            return intRes;    
        }
    }
}

将return intRes放在try块中可以使我摆脱该错误,但是随后出现一个错误,指出并非所有代码路径都返回一个值.我理解这些错误,但是我仍然不明白为什么它不允许我编译,try块每次都执行正确吗?

Putting return intRes inside the try block allows me to get rid of that error, but then an error crops up saying not all code paths return a value. I understand the errors, but I still don't understand why it won't allow me to compile, the try block gets executed every time right?

我还知道将0分配给intRes会消除该错误.

I also know that assigning 0 to intRes will get rid of that error.

此致

推荐答案

编译器正确.并非总是分配变量.

The compiler is right. The variable is not always assigned.

如果转换失败,则分配永远不会发生,并且执行将继续在catch块内进行,在该块中您再次调用该函数,但是您忘记了将该调用的返回值分配给变量:

If the conversion fails, the assignment never happens, and the execution continues inside the catch block, where you call the function again, but you have forgotten to assign the return value of that call to the variable:

catch (Exception ex)
{
  Console.WriteLine("Please enter a numeric value.\n");
  intRes = readValue(strPrompt);
}


这是使用 while TryParse 的另一种实现:

static int readValue(string strPrompt) {
  int intRes = 0;
  bool done = false;
  while (!done) {
    Console.WriteLine(strPrompt);
    if (Int32.TryParse(Console.ReadLine(), out intRes) {
      done = true;
    } else {
      Console.WriteLine("Please enter a numeric value.\n");
    }
  }
  return intRes;    
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆