C#中:未分配的局部变量的用途,使用foreach,如果 [英] C#: Use of unassigned local variable, using a foreach and if

查看:312
本文介绍了C#中:未分配的局部变量的用途,使用foreach,如果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的下面的代码:结果
我得到的错误,使用未分配的本地变量的
我敢肯定,这是死的简单,但是我百思不得其解..

 公共字符串return_Result(字符串[,] RssData,INT marketId)
{
字符串结果;
的foreach(在RssData VAR项)
{
如果(item.ToString()== marketId.ToString())
{
结果= item.ToString( );
}
,否则
{
结果=;
}

}
返回结果;
}


解决方案

初始化的结果,当你把它声明。如果集合为空既不的分支的if语句将永远不会采取并返回之前的结果将永远不会被分配。

 公共字符串return_Result(字符串[,] RssData,INT marketId)
{
字符串结果=;
的foreach(在RssData VAR项)
{
如果(item.ToString()== marketId.ToString())
{
结果= item.ToString( );
}
}
返回结果;
}


I have this following code:
I get the error, "Use of un-Assigned Local variable" I'm sure this is dead simple, but im baffled..

    public string return_Result(String[,] RssData, int marketId)
    {
        string result;
        foreach (var item in RssData)
        {
            if (item.ToString() == marketId.ToString())
            {
                result = item.ToString();
            }
            else
            {
                result = "";
            }

        }
        return result;
    }

解决方案

Initialize result when you declare it. If the collection is empty neither of the branches of the if statement will ever be taken and result will never be assigned before it is returned.

public string return_Result(String[,] RssData, int marketId)
{
    string result = "";
    foreach (var item in RssData)
    {
        if (item.ToString() == marketId.ToString())
        {
            result = item.ToString();
        }
    }
    return result;
}

这篇关于C#中:未分配的局部变量的用途,使用foreach,如果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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