C# 为什么编译错误“使用未分配的局部变量”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9233000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why compile error "Use of unassigned local variable"?
提问by theknut
My code is the following
我的代码如下
int tmpCnt;
if (name == "Dude")
tmpCnt++;
Why is there an error Use of unassigned local variable tmpCnt? I know I didn't explicitly initialize it but due to Default Value Tablea value type is initialized with 0anyways. The reference also reminds me:
为什么会出现错误Use of unassigned local variable tmpCnt?我知道我没有明确初始化它,但是由于默认值表,0无论如何都会初始化一个值类型。参考文献还提醒我:
Remember that using uninitialized variables in C# is not allowed.
请记住,不允许在 C# 中使用未初始化的变量。
But why do I have to do it explicitly if it's already done by default? Wouldn't it gain performance if I wouldn't have to do it? Just wondering...
但是,如果默认情况下已经完成,为什么我必须明确地这样做?如果我不必这样做,它不会获得性能吗?就是想...
采纳答案by James Michael Hare
Local variables aren't initialized. You have to manually initialize them.
局部变量未初始化。您必须手动初始化它们。
Membersare initialized, for example:
成员被初始化,例如:
public class X
{
private int _tmpCnt; // This WILL initialize to zero
...
}
But local variables are not:
但局部变量不是:
public static void SomeMethod()
{
int tmpCnt; // This is not initialized and must be assigned before used.
...
}
So your code must be:
所以你的代码必须是:
int tmpCnt = 0;
if (name == "Dude")
tmpCnt++;
So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.
所以总而言之,成员被初始化,本地人没有。这就是为什么您会收到编译器错误的原因。
回答by Msonic
See this threadconcerning uninitialized bools, but it should answer your question.
请参阅有关未初始化 bool 的线程,但它应该可以回答您的问题。
Local variables are not initialized unless you call their constructors (new) or assign them a value.
除非您调用它们的构造函数(新)或为它们赋值,否则不会初始化局部变量。
回答by Cody Gray
Local variables are not automatically initialized. That only happens with instance-level variables.
局部变量不会自动初始化。这只发生在实例级变量上。
You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the newoperator.
如果要初始化局部变量,则需要显式初始化它们。在这种情况下,(如链接的文档所解释的)通过设置值 0 或使用new运算符。
The code you've shown does indeed attempt to use the value of the variable tmpCntbefore it is initialized to anything, and the compiler rightly warns about it.
您显示的代码确实尝试在将变量tmpCnt初始化为任何值之前使用它的值,并且编译器正确地警告了它。
回答by nabrond
The default value table only applies to initializing a variable.
默认值表仅适用于初始化变量。
Per the linked page, the following two methods of initialization are equivalent...
根据链接页面,以下两种初始化方法是等效的...
int x = 0;
int x = new int();
In your code, you merely defined the variable, but never initialized the object.
在您的代码中,您只是定义了变量,但从未初始化过对象。
回答by dasblinkenlight
Default assignments apply to class members, but not to local variables. As Eric Lippert explained it in this answer, Microsoft could haveinitialized locals by default, but they choose not to do it because using an unassigned local is almost certainly a bug.
默认赋值适用于类成员,但不适用于局部变量。正如 Eric Lippert 在这个答案中解释的那样,Microsoft可以默认初始化 locals,但他们选择不这样做,因为使用未分配的 local 几乎肯定是一个错误。
回答by Sofian Hnaide
While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules. Value types can NOT be null==> the compiler guarantes that. If you ask how? the error message you got is the answer. Once you call their constructors, they got inialized with their default values.
虽然值类型有默认值并且不能为空,但它们也需要显式初始化才能使用。您可以将这两条规则视为并列规则。值类型不能为空==> 编译器保证这一点。如果你问怎么做?你得到的错误信息就是答案。一旦你调用它们的构造函数,它们就会被初始化为默认值。
int tmpCnt; // not accepted
int tmpCnt = new Int(); // defualt value applied tmpCnt = 0
回答by Joe
The following categories of variables are classified as initially unassigned:
以下类别的变量被归类为初始未分配:
- Instance variables of initially unassigned struct variables.
- Output parameters, including the this variable of struct instance constructors.
- Local variables , except those declared in a catch clause or a foreach statement.
- 最初未分配的结构变量的实例变量。
- 输出参数,包括 struct 实例构造函数的 this 变量。
- 局部变量,除了在 catch 子句或 foreach 语句中声明的那些。
The following categories of variables are classified as initially assigned:
以下类别的变量被归类为初始分配:
- Static variables.
- Instance variables of class instances.
- Instance variables of initially assigned struct variables.
- Array elements.
- Value parameters.
- Reference parameters.
- Variables declared in a catch clause or a foreach statement.
- 静态变量。
- 类实例的实例变量。
- 初始分配的结构变量的实例变量。
- 数组元素。
- 值参数。
- 参考参数。
- 在 catch 子句或 foreach 语句中声明的变量。
回答by Damith
local variables don't have a default value.
局部变量没有默认值。
They have to be definitely assigned before you use them. It reduces the chance of using a variable you think you've given a sensible value to, when actually it's got some default value.
在您使用它们之前,必须明确分配它们。它减少了使用您认为已赋予合理值的变量的机会,而实际上它有一些默认值。
回答by Ronika
IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize
Assign value(_getCurrentHolidayList) inside the loop
在循环内分配 value(_getCurrentHolidayList)
foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
{
if (_holidayItem.CountryId == Countryid)
_getCurrentHolidayList = _holidayItem.Holiday;
}
After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.
在您将本地变量传递给另一种方法后,如下所示。它抛出错误(使用未分配的变量)。即使在声明时提到可为空。
var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);
if you mentioned like below, It will not throw any error.
如果你在下面提到,它不会抛出任何错误。
IEnumerable<DateTime?> _getCurrentHolidayList =null;
回答by zar
A very dummy mistake but you can get this with a class too if you didn't instantiate it.
一个非常愚蠢的错误,但是如果您没有实例化它,您也可以通过一个类来获得它。
BankAccount account;
account.addMoney(5);
The above will produce the same error where as:
以上将产生相同的错误,其中:
class BankAccount
{
int balance = 0;
public void addMoney(int amount)
{
balance += amount;
}
}
Do the following to eliminate the error
执行以下操作以消除错误
BankAccount account = new BankAccount();
account.addMoney(5);

