我想知道如果我能得到一个手请。有人可以向我解释为什么我的字符串sqrt
未在finally
块中分配吗?为什么我必须申报?为什么不能在try或catch语句中声明?这将使编码更加乏味,更有组织。本地变量未分配的问题使用Try,catch,最后
private void btnDisplay_Click(object sender, EventArgs e)
{
int number;
string sqrt;
try
{
number = Convert.ToInt32(tbInput.Text);
//Why cant i just have it as "number=COnvert.ToDouble(tbInput.Text)?//
Convert.ToDouble(number);
if (number < 0)
{
throw new NegativeNumberException();
}
sqrt = Math.Sqrt(number).ToString();
}
catch (FormatException error)
{
lbOutput.Items.Add(error.Message);
lbOutput.Items.Add("The input should be a number.");
sqrt = "not able to be calculated";
}
catch (NegativeNumberException neg)
{
lbOutput.Items.Add(neg.Message);
sqrt = "not able to be calculated";
}
finally
{
//Here is where i am having the issue "Unassigned local variable"//
lbOutput.Items.Add("Square Root " + sqrt);
}
}
class NegativeNumberException : Exception
{
public NegativeNumberException()
: base("Number can’t be negative")
{
}
}
}
}
什么我试图在finally块来实现是在列表框中无论什么开方的值是显示“平方根”和“开方”。如果我将sqrt输出到任何其他块的列表框中,它就可以工作(因为它已被声明)。有谁知道我该怎么做?我敢打赌这可能也很简单。我不是故意要咆哮,或者只是在过去的12个小时里我一直坚持下去,所以我开始感到失败。我很感谢大家的帮助,我真的这么做。
http://stackoverflow.com/questions/94977/why-arent-variables-declared-in-try-in-scope-in-catch-or-finally这里是你的答案:) – Zze
声明变量号为双倍比你可以做这个数字= Convert.ToDouble(number); – Mairaj
好吧,用这种方式来看看吧:'finally'保证运行* always *,不管是什么(不包括停电等)。那么在'sqrt'设置之前'catch'块中的某些东西出错了怎么办?或者,如果抛出一个异常,你不知道该怎么办?然后'sqrt'没有设置,换句话说就是“未分配”。因此,解决这个问题的最简单方法是立即将它初始化为* something *。像:'string sqrt = string.Empty;'或者甚至'string sqrt = null;'。 – Corak