一般问题C# [英] General question c#

查看:49
本文介绍了一般问题C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码片段类似于

My code snip is something like

bool success;
foreach (object item in items)
{
    if (something)
        sucess = true;
}
if (success)
    break;



它给我错误
使用未分配的局部变量成功"

我知道如果我像这样初始化它



It gives me error
Use of unassign local variable ''success''

I know that if I initialize it like

bool success = false;


会很好用的.

但是我的问题是为什么呢?如果bool变量的默认值为false


谢谢

:)


it will work fine.

but My question is why so? if default value of bool variable is false


Thanks

:)

推荐答案

在c#中,仅为成员变量分配了默认值,所有本地变量都需要进行显式分配.

这是一条基本规则,即您不能访问未分配任何值的变量.在您的情况下,编译器不确定foreach 循环是否运行,并且与for循环中的if条件相同,这就是为什么会出现错误.

例如

In c# only the member variables gets assigned with the default values, all the local vaiabiable needs to be assigned explictely.

This is basic rule that you can’t access a variable which is not assigned any value. In you case compiler is not sure that if foreach loop will run or not and same with the if condition within for loop, thats why you are getting the error.

For example

bool success;

if(something)
{
 success= false;
}

// you will get error





bool success;

If(something)
{
success=false;
}
else
{
success=true;
}

//you will not get any error, because success will get a value in any case.


Khaniya写道:
Khaniya wrote:

sucess = true;

sucess = true;


拼写错误.您应该具有:


Bad spelling. You should have:

success = true;


当然,另外两个答案是正确的.


Of course, the other two answers are right.


我不知道为什么C#会忽略变量的默认值,但是如果您创建它,并且只有一些代码路径为其指定,您会收到此错误. C#很烂.
I don''t know why C# ignores the default values for variables, but if you create it, and only some code paths assign it, you get this error. C# sucks like that.


这篇关于一般问题C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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