2012-03-09 75 views
1

我有一個字符串errMsg在輸入文件被讀取後打印。在驗證完成後,如果success==false它調用的方法PrintErrorMessage(string)ref類型,StringBuilder

//Validations 
//First Validation: checks the value of input string realization. 
success = Numerical.Check("Realizations", inputs.realizations.ToString(), out ltester, out errMsg); 
sb.AppendLine(errMsg); 

//Second Validation: checks the value of the input string diameter. 
success = Numerical.Check("Pipe Outside Diameter", inputs.pipeOD.ToString(), out dtester, out errMsg); 
sb.AppendLine(errMsg); 
if (!success) 
{ 
    PrintErrorMessage(success, errTitle, sb.ToString()); 
} 

此處,我打印了錯誤的方法:

Streamwriter swpt = new Streamwriter(....); 
private void PrintErrorMessage(bool success, string errTitle, string errMsg) 
{ 
    if (!success) 
    { 
     swRpt.WriteLine(errTitle + errMsg); 
    } 
} 

問題是這樣的:而不是在每一個追加StringBuilder的在每次驗證之後,我可以使用ref類型並將它傳遞給PrintErrorMessage函數並將其添加到那裏?

+0

'StringBuilder'可能是一個糟糕的選擇。弦有多大?這個代碼是在緊密的循環中調用的嗎?你有性能統計數據表明這是一個問題領域? http://www.yoda.arachsys.com/csharp/stringbuilder.html – asawyer 2012-03-09 23:01:07

+0

是的,並且由於它是一個對象,所以默認情況下它將通過引用傳遞。 – 2012-03-09 23:01:17

+0

也許這只是僞代碼,因爲第二次測試會破壞第一個(成功)的結果。但是,從這種情況下,我會說使用StringBuilder有點過分 – Steve 2012-03-09 23:07:35

回答

5

Instead of appending the stringbuilder at each an everystep after each validation, can I use a ref type and pass it in the PrintErrorMessage function and append it there

您可以通過它沒有ref和追加到它。 StringBuilder是一個參考類型

+0

你能告訴我怎麼做。我是否需要在每次驗證後調用PrintErrorMessage。我更喜歡在所有驗證完成後調用它 – user575219 2012-03-10 02:06:04

3

當然。你甚至不需要聲明一個'ref'類型參數 - 因爲StringBuilder本身就是一個引用類型,它會被ref自動傳遞。

+0

你能告訴我怎麼做。我是否需要在每次驗證後調用PrintErrorMessage。我更喜歡在所有的驗證完成後調用它 – user575219 2012-03-10 02:06:27

相關問題