【问题标题】:How can I return multiple string values using while loop+如何使用while循环返回多个字符串值
【发布时间】:2013-12-16 03:51:44
【问题描述】:

这就是我想要的: 类中的一种方法,它将迭代地返回某个列的值。调用该方法时,此值将添加到组合框。这是我的尝试:

  public string FillCombo()
      {
            string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
            string query = "Select * from categorias";
            SqlConnection conn = new SqlConnection(connstring);
            SqlCommand command = new SqlCommand(query, conn);
            SqlDataReader read;
                conn.Open();
                read = command.ExecuteReader();
                while (read.Read())
                {
                    string combodata = read.GetString(1);
                    return (combodata); 
                }
               return null;
        }

但是,当调用此方法时,它只会将第一行返回到 de combobox,而不是其他值。

【问题讨论】:

  • 您希望它如何返回多个值?你希望调用者看到什么?听起来您应该返回 List<string> 或类似的东西。
  • 这只会返回一个结果,因为您正在返回第一项并在数据读取器有机会读取下一项之前退出函数。您期望的结果是什么 - 您只是想用数据库中的值填充组合框吗?

标签: c# loops iterator return


【解决方案1】:

它叫yield

http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx

来自手册

public static System.Collections.IEnumerable Power(int number, int exponent)
{
    int result = 1;

    for (int i = 0; i < exponent; i++)
    {
        result = result * number;
        yield return result;
    }
}

yield 将在循环完成后发送循环内部的返回结果集合。

您可以使用循环周围的 try/finally 块来关闭数据连接。

  public IEnumerable FillCombo()
  {

        SqlConnection conn = new SqlConnection(connstring);
        SqlCommand command = new SqlCommand(query, conn);
        SqlDataReader read;
        conn.Open();
        read = command.ExecuteReader();
        try
        {
            while (read.Read())
            {
                yield return read.GetString(1);
            }
        }
        finally
        {
            read.close();
            conn.close();
        }
    }

C# 的一个很酷但经常被忽视的特性

【讨论】:

  • @MikeChristensen 大多数数据连接都支持IDispose,因此将循环包装在using 语句中将在函数存在时关闭阅读器。
  • 我认为如果数据读取器在实现枚举之前关闭,你会得到一个异常。我认为您最好返回 List&lt;String&gt; 或 String[]
  • @MikeChristensen 你觉得我的编辑怎么样?尚未测试,但应该可以。
  • 是的,我也必须测试一下。如果 finally 块在 之后执行,则您遍历返回的枚举(这很酷),那么它应该可以工作!我很好奇,所以我会在有空的时候试一试。
【解决方案2】:

考虑使用字符串列表作为输出。对您的代码进行以下细微更改应该会有所帮助...

public List<string> FillCombo()
{
    List<string> comboList = new List<string>();
    string connstring = "Data Source=HP\\SQLEXPRESS;Initial Catalog=Arana;Integrated Security=True";
    string query = "Select * from categorias";
    SqlConnection conn = new SqlConnection(connstring);
    SqlCommand command = new SqlCommand(query, conn);
    SqlDataReader read;
    conn.Open();
    read = command.ExecuteReader();
    while (read.Read())
    {
        string combodata = read.GetString(1);
        comboList.Add(combodata);
    }
    return comboList;
}

祝你好运!

【讨论】:

    猜你喜欢
    • 2015-01-15
    • 2019-02-20
    • 1970-01-01
    • 2021-03-14
    • 2013-12-18
    • 2014-04-22
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多