2016-07-30 66 views
1

我使用参考参数来返回多个信息。像,C#参考参数的用法

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<string, int> totalInfos = new Dictionary<string, int> 
{ 
    { "totalTransaction", 0 }, 
    { "outTransaction", 0 }, 
    { "totalRecord", 0 } 
}; 

var record = reports.GetTransactionReport(searchModel, out totalInfos); 

但仍然不够好,因为关键字符串不被承诺,它就像硬编码。

我是否需要使用常量作为键?或针对这种情况的更好的解决方案?

+3

为什么不创建一个使用属性公开所有信息的类? –

+1

尽管并非所有这些警告都很重要,但我确实同意这一点:https://msdn.microsoft.com/zh-cn/library/ms182131.aspx除非您真正了解为什么需要“out”参数,否则我会避免他们。 – starlight54

回答

5

只需使用一个类。并完全避免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 = ... 
    }; 
} 
+0

非常感谢! –