为什么我会收到编译错误“使用未分配的局部变量"? [英] Why did I get the compile error "Use of unassigned local variable"?

查看:34
本文介绍了为什么我会收到编译错误“使用未分配的局部变量"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下

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.

这篇关于为什么我会收到编译错误“使用未分配的局部变量"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆