0

我在 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 参数,但我不确定调用者将如何实际检索数据。有什么帮助吗?

4

1 回答 1

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 文档。out

备择方案:

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

    ... in the method ...
    return Tuple.Of(result, recordsAffected);
    
    ... in the caller ...
    var results = GetRecordSummary();
    int result = results.Item1;
    int recordsAffected = results.Item2;
    
于 2012-09-03T06:18:18.393 回答