C#引用参数用法

本文关键字:用法 参数 引用 | 更新日期: 2023-09-27 17:59:22

我使用引用参数来返回多个信息。比如

int totalTransaction = 0;
int outTransaction = 0;
int totalRecord = 0;
var record = reports.GetTransactionReport(searchModel, out totalTransaction, out outTransaction, out totalRecord);

//方法是这样的,

public List<TransactionReportModel> GetAllTransaction(
            TransactionSearchModel searchModel, 
            out totalTransaction,
            out totalTransaction,
            out totalRecord) {

    IQueryable<TransactionReportModel> result;
    // search
    return result.ToList();
}

但我不喜欢长参数,所以我试图用Dictionary用单个参数来清理它。

Dictionary<string, int> totalInfos = new Dictionary<string, int>
{
    { "totalTransaction", 0 },
    { "outTransaction", 0 },
    { "totalRecord", 0 }
};
var record = reports.GetTransactionReport(searchModel, out totalInfos);

但仍然不够好,因为没有承诺关键字符串,这就像硬录音一样。

密钥需要使用Constant吗?或者有更好的解决方案吗?

C#引用参数用法

只需使用一个类。并完全避免out参数:

class TransactionResult
{
    public List<TransactionReportModel> Items { get; set; }
    public int TotalTransaction { get; set; }
    public int OutTransaction { get; set; }
    public int TotalRecord { get; set; }
}

public TransactionResult GetAllTransaction(TransactionSearchModel searchModel)
{
    IQueryable<TransactionReportModel> result;
    // search
    return new TransactionResult
    { 
        Items = result.ToList(),
        TotalTransaction = ...,
        OutTransaction = ...,
        TotalRecord = ...
    };
}