为什么我会收到编译错误“使用未分配的局部变量"?
我的代码如下
int tmpCnt;
if (name == "Dude")
tmpCnt++;
为什么会出现错误Use of unassigned local variable 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.