未分配的局部变量&QUOT使用;?;为什么编译出错&QUOT

未分配的局部变量&QUOT使用;?;为什么编译出错&QUOT

问题描述:

我的code是以下

int tmpCnt;  
if (name == "Dude")  
   tmpCnt++;  

为什么会出现错误使用未分配的局部变量tmpCnt 的?我知道我没有明确地初始化,但由于默认值表的值类型初始化与 0 反正。参考也提醒我:

Why is there an error Use of unassigned local variable tmpCnt? I know I didn't explicitly initialize it but due to Default Value Table a value type is initialized with 0 anyways. 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? Just wondering...

局部变量进行初始化。你必须手动初始化它们。

Local variables aren't initialized. You have to manually initialize them.

成员的初始化,例如:

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.

    ...
}

所以,你的code必须是:

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.