从调用程序中的函数和填充变量(2)返回多个值
本文关键字:返回 变量 填充 程序 调用 函数 | 更新日期: 2024-09-19 04:55:34
我在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;
}
我想从这个函数中得到两个值,并将其返回给两个不同的变量。
从另一个类中,我将如何填充两个变量?
B类:
int RESULT = RecordSummary();
int RECORDS_AFFECTED = RecordSummary();
我一直在阅读元组并使用out参数,但我不确定调用方将如何实际检索数据。有什么帮助吗?
以下是如何使用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);
有关更多详细信息,请参阅out
上的MSDN文档。
备选方案:
- 创建自己的类型来封装这两个值,并返回该类型的值
如果使用.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;