简体   繁体   English

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

[英]error: Use of unassigned local variable

I have this method: 我有这种方法:

public static void Add(int _Serial, string _Name, long? _number1, long? _number2)
{
    // ...
}

and use this code for send date to method: 并使用以下代码将日期发送到方法:

long? _num1;
long? _num2;
if (txtNumber1.Text != null && txtNumber1.Text != "")
{
    _num1= long.Parse(txtNumber1.Text);
}
if (txtNumber2.Text != null && txtNumber2.Text != "")
{
    _num2= long.Parse(txtNumber2.Text);
}
Add(22, "Kati", _num1, _num2)

but Error _num1 & _num2 in Add(...) . 但是在Add(...)错误_num1_num2

Error: 错误:

Use of unassigned local variable '_num1' 使用未分配的局部变量“ _num1”

Use of unassigned local variable '_num2' 使用未分配的局部变量“ _num2”

The compiler doesn't know whether those if statements are going to be executed, so it considers the worst case scenario, and realizes that one or both variables may not be initialized before they are used in Add. 编译器不知道是否要执行这些if语句,因此它考虑了最坏的情况,并意识到在Add中使用一个或两个变量之前可能不会对其进行初始化。

The solution is to initialize them at declaration, like this: 解决方案是在声明时初始化它们,如下所示:

long? _num1 = null;
long? _num2 = null;

Yes, you must initialize local variables before usage. 是的,使用前必须初始化局部变量。 But in this case you can remove those variables (see refactoring below). 但是在这种情况下,您可以删除这些变量(请参见下面的重构)。

There is nice method String.IsNullOrEmpty in the box. 框中有一个不错的方法String.IsNullOrEmpty You can use it to verify if some string has value "" or null . 您可以使用它来验证某个字符串是否具有值""null Also, I'd moved parsing nullables to separate method: 另外,我将解析可空值移动到单独的方法:

private long? ParseNullableLong(string s)
{
    return String.IsNullOrEmpty(s) ? null : (long?)Int64.Parse(s);
}

Then declare two properties for retrieving values from UI (of course, consider better names): 然后声明两个属性以从UI检索值(当然,考虑使用更好的名称):

private long? Number1
{
    get { return ParseNullableLong(txtNumber1.Text); }
}

private long? Number2
{
    get { return ParseNullableLong(txtNumber2.Text); }
}

And now all your code will look like: 现在,您的所有代码将如下所示:

Add(22, "Kati", Number1, Number2);

Kendall Frey answers your question. 肯德尔·弗雷(Kendall Frey)回答您的问题。 I just would like to suggest you another approach for parsing numbers here. 我只是想向您建议这里解析数字的另一种方法。

long? _num1 = null;
long result;

if (Int64.TryParse(txtNumber1.Text, out result)) {
    _num1 = result;
}

This is easier an safer, as TryParse will not throw an exception, even if the text is null, empty or not a number. 这样更容易安全,因为TryParse不会引发异常,即使文本为null,空或不是数字。

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

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