从函数返回多个值并在调用者中填充变量(2)

时间:2012-08-03 15:40:08

标签: c# parameters tuples out

我在A班有一个功能:

public int RecordSummary()
        {
            int result = 0;
            int recordsAffected = 0;

            SqlCommand cmd = new SqlCommand("spIATRecordSummary", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            var returnParameter = cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int);
            returnParameter.Direction = ParameterDirection.ReturnValue;

            try
            {
                conn.Open();
                recordsAffected = cmd.ExecuteNonQuery();
                result = Convert.ToInt32(returnParameter.Value);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message.ToString());
            }
            finally
            {
                conn.Close();
            }
            -- I want to return these two: 
            return result;
            return recordsAffected;
        }

我想从此函数中获取2个值并将其返回到两个不同的变量。

从另一课开始,我将如何填充两个变量?

B组:

int RESULT = RecordSummary();
int RECORDS_AFFECTED = RecordSummary();

我一直在阅读元组并使用out参数,但我不确定调用者将如何实际检索数据。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

以下是 使用out参数的方式:

int GetRecordSummary(out int recordsAffected)
{
    // If necessary - basically this variable *must* be definitely
    // assigned by the time you return; your code currently just
    // catches exceptions thrown by the block that would assign
    // a value :(
    recordsAffected = -1;
    ...
    // Code as before
    ...
    return result;
}

然后用:

调用它
int recordsAffected;
int result = GetRecordSummary(out recordsAffected);

有关详细信息,请参阅MSDN documentation on out

备选方案:

  • 创建您自己的类型以封装这两个值,并返回该类型的值
  • 如果您使用的是.NET 4或更高版本,请返回Tuple<int, int>

    ... in the method ...
    return Tuple.Of(result, recordsAffected);
    
    ... in the caller ...
    var results = GetRecordSummary();
    int result = results.Item1;
    int recordsAffected = results.Item2;