2016-07-30 65 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

非常感謝! –