函数返回值,不是所有的代码路径都返回 [英] function return value, not all code paths return

查看:98
本文介绍了函数返回值,不是所有的代码路径都返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码

  Global.dbCon.Open(); 
列表< int> idQuestions = new List< int>();
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if(Global.reader.HasRows)
while(Global.reader.Read())
{
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0) );
idQuestions.Add(idQuestion);
}
Global.dbCon.Close();
foreach(int id在idQuestions中)
messageBox.Show(id.ToString());

我尝试编辑它以使用函数(class),所以我可以像这样多次调用它

  private int sqlReader(string kalimatSql)
{
int sqlReader(string kalimatSql){
Global.dbCon.Open();
列表< int> idQuestions = new List< int>();
Global.reader = Global.riyeder(kalimatSql);
if(Global.reader.HasRows)
while(Global.reader.Read())
{
int idQuestion = Convert.ToInt32(Global.reader.GetValue(0) );
idQuestions.Add(idQuestion);
}
Global.dbCon.Close();
foreach(int id在idQuestions中)
return id;
}

但它不工作,因为不是所有的代码路径都返回一个值... I想知道什么是正确的方法来做到这一点? 解决方案

foreach'循环运行零时间?,换句话说,当你的'idQuestions'长度为零时,你的代码应该返回什么值?为了摆脱这个,你需要什么值?将此代码更改为

  if(idQuestions.Count> 0)
{
foreach(int id在idQuestions中){
return id;
}
}
else
return -1;


hi I have code like this

Global.dbCon.Open();
List<int> idQuestions = new List<int>();
kalimatSql = kalimatSql;
Global.reader = Global.riyeder(kalimatSql);
if (Global.reader.HasRows)
    while (Global.reader.Read())
    {
        int idQuestion = Convert.ToInt32(Global.reader.GetValue(0)); 
        idQuestions.Add(idQuestion);
    }
Global.dbCon.Close();
foreach (int id in idQuestions)
    messageBox.Show(id.ToString());

I try to make edit it to function (class) so I can call it many times like this

private int sqlReader(string kalimatSql)
{
    int sqlReader(string kalimatSql){
    Global.dbCon.Open();
    List<int> idQuestions = new List<int>();
    Global.reader = Global.riyeder(kalimatSql);
    if (Global.reader.HasRows)
        while (Global.reader.Read())
        {
            int idQuestion = Convert.ToInt32(Global.reader.GetValue(0));
            idQuestions.Add(idQuestion);
        }
    Global.dbCon.Close();
    foreach (int id in idQuestions)
        return id;
}

but it's not working because not all code paths return a value... I wonder what's the correct way to do it?

解决方案

this error occurred because, what will happened (or returned) when your last 'foreach' loop runs zero time?, in other sense what value should your code return when your 'idQuestions' has zero length?

in order to get rid of this, you change this code as

if(idQuestions.Count > 0)
{
    foreach (int id in idQuestions) {
       return id;
    }
}
else
    return -1;

这篇关于函数返回值,不是所有的代码路径都返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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