为什么会出现编译错误“使用未分配的局部变量"? [英] Why did I get the compile error "Use of unassigned local variable"?
问题描述
我的代码如下
int tmpCnt;
if (name == "Dude")
tmpCnt++;
为什么会出现错误使用未分配的局部变量tmpCnt"??
我知道我没有明确初始化它,但是由于 默认值表 值类型始终用 0
初始化.该参考文献还提醒我:
I know I didn't explicitly initialize it, but due to Default Value Table a value type is initialized with 0
anyway. The reference also reminds me:
请记住,不允许在C#中使用未初始化的变量.
Remember that using uninitialized variables in C# is not allowed.
但是,如果默认情况下已经完成,为什么还要显式执行呢?如果我不必这样做,它是否会获得性能?
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?
推荐答案
局部变量未初始化.您必须手动初始化它们.
Local variables aren't initialized. You have to manually initialize them.
成员已初始化,例如:
public class X
{
private int _tmpCnt; // This WILL initialize to zero
...
}
但是局部变量不是:
public static void SomeMethod()
{
int tmpCnt; // This is not initialized and must be assigned before used.
...
}
因此您的代码必须是:
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.
这篇关于为什么会出现编译错误“使用未分配的局部变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!